Let's say that you create 2 database tables, a User table and a Company table. A user can be part of a company so the User table has a CompanyId foreign key. Then you go ahead and create your Entity Framework Model, which recognizes the foreign key and creates the relationship between the business objects. You create a registration form that allows the saving of a user, and you have a Company dropdown on there where the user can pick which company they belong to. When they click save, you want to not only create the User but set up the correct relation between that user and the selected company. If you're new to the Entity Framework, your first attempt will probably look something like this:
using (MyEntities dataContext = new MyEntities())
{
User user = new User();
user.Company = new Company();
user.Company.CompanyId = 1;//TODO: get selected company id
dataContext.AddToUser(user);
dataContext.SaveChanges();
}
However this won't work, it'll most likely throw an exception about how you need to attach an existing key rather than trying to add a new one. The problem is you're trying to add a user but also are trying to add the company, when the company already exists. The solution is to add a reference to the company rather than a new company object:
using (MyEntities dataContext = new MyEntities())
{
User user = new User();
user.CompanyReference.EntityKey = new EntityKey("MyEntities.Company", "CompanyId", 1);
dataContext.AddToUser(user);
dataContext.SaveChanges();
}
This will correctly add the company reference to the user table.
Now let's say that you have a grid where you want to view a list of all users and which companies they belong to. Again, your first stab might look like this:
using (MyEntities dataContext = new MyEntities())
{
return dataContext.User.ToList();
}
If you view sql profiler while running this, you'll see that it only grabs the record from the User table, it doesn't know to grab the associated Company record as well. To fix this, we use the Include statement to implement "eager loading", which will also load the company object related to the user:
using (MyEntities dataContext = new MyEntities())
{
return dataContext.User.Include("Company").ToList();
}
This will fill the User.Company object and you're good to go...
6d928c00-03e4-4897-a7fb-c7b4e677e3d3|0|.0