LINQ to SQL - No Foreign Keys - c#

No foreign keys defined in the database. So I've setup associations.
problem: can't seem to be able to reference the Role table as expected:
I can get as far as u.UserNamesInRole then can't make the jump to role table.
IEnumerable<fmwebapp1.Old_App_Code.TelerikUsersDataContext.User> userList = (from u in dbTelerik.Users
where u.UsersInRoles.Role.Name = "admin"
select u.UsersInRoles);

where u.UsersInRoles.Role.Name = "admin"
That is incorrect syntax. You need ==.

In a many-to-many relationship, when I want results from one side only, filtered by values on the other side, I usually start my query in the middle of the relation:
To get a role's users:
var users = from ur in context.UsersInRole
where ur.Role.Name == "admin"
select ur.User;
To get a user's roles:
var roles = from ur in context.UsersInRole
where ur.User.UserName == "Jon"
select ur.Role

It would be easiest to add an FK relationship in your database and reimport the tables. EF will then do all the work for you.
If that's not possible, try adding an Association from Role to User and then set the Association Set Name to UsersInRole. Delete the UsersInRole entity from the designer.
You could also compare the EDMX file generated from importing a 'proper' FK relationship between two tables with what you have in your EDMX and then hand edit the XML to match.

Related

How to select data from entity framework without selecting its icollection(foreign table)

I am using C# to select data from my database. Now i have two table, the first one is aspnetuser, the second one is aspnetuserroles, the aspnetuserroles have the foreign key linkage with aspnetuser table, when i perform the following query
db.AspNetUsers.ToList()
the aspnetroles data will appeared in the aspnetusers data. This will cause my datatable unable to display its data because datatable expect one value in one column parameter. If the aspnet roles data inside that json, it will appear as multiple row and datatable dont accept it.. If i remove that foreign key linkage, my datatable will display without any error.
In this case, what i want is, how to select aspnetusers table without pulling out its foreign table. For eg
db.AspNetUsers.Select(x=>x.AspNetUsers).ToList();
Turn off the LazyLoading. So that the children will not be fetched automatically.
try doing something like this (good for keeping the return object light and leave behind any unwanted columns):
(I have just made up some col name, but you get the idea.)
var result = (from a in db.AspNetUsers
select new AspNetUser { Name = a.Name,
othercol1 = a.othercol1,
othercol2 = a.othercol2,
}).ToList();
Footnote: In reality it is generally not good practice to return the actual db Entity to the front end so you might want to have your own Data Transfer Objects (DTO).
You configured that in the mappings using the Fluent API's methods
HasOptional
HasMany
Ignore
etc. But normally, I create schema-bound views in database and then map that in EF. It works really well in cases when we're only interested in a flattened query without all the joints.
Or use Linq to EF projections as JonhB's answer...
var result = (from a in db.AspNetUsers
select new AspNetUser { Name = a.Name,
...
}).ToList();
Just make sure you don't call ToList on db.AspNetUsers because that would materialize the query on AspNetUsers and all it's foreign key references and as result the projection is done in-memory after the query returns

Similar Columns Relation in Entity Framework

I use Entity Framework 4 on C# Winforms.
I have a SQL Server database with 2 tables like this:
Users table:
UserId (int) (PK)
UserName
Products table:
ProductId (int)(PK)
ProductTitle
UserId1 (int) (foreign key referencing `UserId` in `Users` table)
UserId2 (int) (foreign key referencing `UserId` in `Users` table)
I am modeling SQL Server database in my C# project with Entity Framework (including foreign key columns in model).
Then I get records with this code:
Entities dbEnteties = new Entities();
dbEnteties.ContextOptions.LazyLoadingEnabled = false;
var dbe = dbEnteties.Products.Include("Users");
var result = dbe.ToList();
When I get records from database I see that the UserId1 field has data but UserId2 field is Null.
What's wrong with my C# code? And how can I solve this problem?!
It's perfectly okay for you to have two foreign keys in the Products table pointing to the Users table. I do this all the time, and your reason for doing it is fine.
Since you have turned Lazy Loading off, you need to explicitly ".Include" the navigation properties if you want the query to automatically load them. You're going to have to figure out what the names are for the navigation properties that Entity Framework created automatically for you. I'm assuming you are using the "Database First" model. If that's the case, then double click on your .EDMX file and look at the Products table. You should see a section there called "Navigation Properties". They might be called "User" and "User1". If this is the case, then you need to do the following. Since you have two separate relationships between the tables, you will need two separate ".Include" statements:
dbEnteties.Products.Include(product => product.User);
dbEnteties.Products.Include(product => product.User1);
(Make sure to include using System.Data.Entity; at the very top of your file, otherwise the lambda syntax will not work.)

How to get associated tables with LINQ

let's say I have to tables: "Customer" (parent) & "Address" (child). They are associated, so there is a 1:1 relationship between them.
Table<Customer> table = db.GetTable<Customer>();
var query = from c in table
select p;
Is there a possibility to query against tables that are associated with "Customer" using the selected Customer-tables or do I have to get all Address-tables in a separate query?
Besides if I use a DELETE-command on a Customer-table, does this DELETE all the associated tables too?
Thanks in advance,
Prot
If they are related with a foreign key, then it should be very straight forward. The Address should just be a property of Customer.
var query = from c in table
select c.Address;
Or you could do it with a join if a foreign key doesn't exist.
var query = from c in table
join address in [AddressTable] on c.AddressId equals address.Id
select address;
The type of DELETE you're referring to is called a cascade delete. You'll need to enable it on your foreign key (you'll need an FK for this to work). See this thread.
you don't have to get the address out separately, you should be able to just lazy load the address if you have set up an association in the dbml (i.e the arrow linking the tables).
Instellisense should show the property;
var query = from c in table
select p.Address;
for the delete set up an on delete cascade on your foreign key on the tables themselves and this will delete the associated address every time you delete a customer record.

linq to sql linking objects by multiple ID fields

Im working on a project at work which is pretty much a commissioning manager and i cant seem to figure out how to link the Items table properly in linq to sql.
I have a package detail table that has (among other things)
DepartmentID, CategoryID, ItemID
And the Items table (is actually a database view as its from a different database and is read only in this app) also have these 3 fields but when i add an association with these 3 fields it doesnt add that as a property object ot the PackageDetail class
am i doing something wrong with the association? all the single ones im doing work fine...
I don't believe that Linq-to-SQL can properly model an association with a composite key:
Is it beneficial to use multicolumn (composite) primary keys when using Linq to SQL?
However, you can still load objects with composite keys in a Linq-to-SQL query using an anonymous object as the (single) key:
http://msdn.microsoft.com/en-us/library/bb399391.aspx
have marked those ID fields as Primary keys? Make sure you assign the necessary columns as primary keys and this should work fine. Hope it helps
Ensure the keys are correctly setup with primary key and foreign key relationship. If that still doesn't work, could you consider adding a new key column, rather than relying on composite key?
Last option with LINQ to SQL is usually manually updating the DBML with an XML editor. A normal single key relationship appears as follows:
<Association Name="Schedule_Profile" Member="Schedule" ThisKey="ScheduleID" Type="Schedule" IsForeignKey="true" />
Suggest you try creating the element yourself, and try setting ThisKey to a csv list of columns. The OtherKey attribute may also be of interest.
It looks like you could just use ItemId and ignore the other 2 since that is the most specific qualifier - in other words, Department and Category are fully determined by itemId.
Did you mean a query like this.
var result = from table in dbContext.table1 join table2 in dbContext.table2 join new { table.DepartmentID, table.CategoryID, table.ItemID} equals new {table2.DepartmentID, table2.CategoryID, table2.ItemID}
select table;

Linq to SQL - "This member is defined more than once" error

I have the following linq code...
CMSDataContext dc = new CMSDataContext();
var q = from u in dc.CMSUsers
join d in dc.tblDistricts
on u.DistrictCode equals d.District into orders
select u;
District shows this error:
Ambiguity between 'tblDistrict.District' and 'tblDistrict.District'
Any ideas?
EDIT:
It turns out that I had the same table in two different dbml files. Apparently, I cannot do this. I will have to end up joining a table from one dbml file with another table from a different dbml file. If anyone can enlighten me on how to do this, I will deem it as an answer. Thanks.
If you have a FK releationship between two tables, LINQ-to-SQl will automatically create a property for it.
For example, if you Order object has a CustomerID which is a Foriegn key to the Customers table, Order will automatically have a Customer property. If you already have a Customer property, there will be a conflict.
I had he same problem. The solution was to delete .dbml file from the solution explorer.

Categories

Resources