Entity Framework: Auto-updating foreign key when setting a new object reference

Posted by Adrian Grigore on Stack Overflow See other posts from Stack Overflow or by Adrian Grigore
Published on 2010-06-11T15:16:58Z Indexed on 2010/06/13 22:32 UTC
Read the original article Hit count: 265

Hi,

I am porting an existing application from Linq to SQL to Entity Framework 4 (default code generation).

One difference I noticed between the two is that a foreign key property are not updated when resetting the object reference. Now I need to decide how to deal with this.

For example supposing you have two entity types, Company and Employee. One Company has many Employees.

In Linq To SQL, setting the company also sets the company id:

var company=new Company(ID=1);
var employee=new Employee();
Debug.Assert(employee.CompanyID==0);
employee.Company=company;
Debug.Assert(employee.CompanyID==1); //Works fine!

In Entity Framework (and without using any code template customization) this does not work:

var company=new Company(ID=1);
var employee=new Employee();
Debug.Assert(employee.CompanyID==0);
employee.Company=company;
Debug.Assert(employee.CompanyID==1); //Throws, since CompanyID was not updated!

How can I make EF behave the same way as LinqToSQL? I had a look at the default code generation T4 template, but I could not figure out how to make the necessary changes.

© Stack Overflow or respective owner

Related posts about linq-to-sql

Related posts about entity-framework