How can I use the Entity Framework to establish foreign key relationships?

asp.net-mvc entity-framework foreign-key-relationship

Question

I want to add a new entry to a table in my database that contains a few foreign key associations, but I'm not sure what calls should be performed in what sequence. I currently have the following:

db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.CustomerReference.Attach( ( from c in db.Customer where c.Id == custId select c ).First() );
db.SaveChanges();

On the second line, the code is failing with the message:

Attach is not a valid operation when the source object associated with this related end is in an added, deleted, or detached state. Objects loaded using the NoTracking merge option are always detached.

Any thoughts?

1
5
7/13/2012 7:10:49 AM

Accepted Answer

(We appreciate John fixing the grammar.)

I therefore came to a solution. What you need to do is as follows:

db.Models.Order order = DB.Models.Order.CreateOrder( apple );
order.Customer = (from c in db.Customer where c.Id == custId select c).First();
db.SaveChanges();

That should be helpful, I hope.

8
10/13/2008 2:51:45 PM

Popular Answer

Why not make reference to entities? Your approach will result in an additionalSELECT statement.

Using the is a much better method thanCustomerReference combined with aEntityKey .

order.CustomerReference = new System.Data.Objects.DataClasses.EntityReference<Customers>();
order.CustomerReference.EntityKey = new EntityKey("ModelsEntities.Customers", "Id", custId);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow