How to create foreign key relationships with the Entity Framework?

旧城冷巷雨未停 提交于 2019-12-10 14:23:39

问题


I want to create a new row in my database on a table that has a couple of foreign key relationships and I haven't been able to get a handle on what order and what calls need to be made. This is what I have so far:

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();

The code is failing on the second line there, saying:

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 ideas?


回答1:


(Thanks John for the grammar fixes)

So I figured it out. This is what you have to do:

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();

I hope that helps people.




回答2:


Why not use entity references? Your method will cause an extra SELECT statement.

A much nicer way is to use the CustomerReference class and an EntityKey.

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



回答3:


For update here is some sample code:

using (var ctx = new DataModelEntities())
{

       var result = (from p in ctx.UserRole.Where(o => o.UserRoleId == userRole.UserRoleId)
                              select p).First();

       result.RolesReference.EntityKey = new EntityKey("DataModelEntities.Roles",
                                       "RoleId", userRole.RoleId);

       result.UserRoleDescription = userRole.UserRoleDescription;      
       ctx.SaveChanges();
}


来源:https://stackoverflow.com/questions/197747/how-to-create-foreign-key-relationships-with-the-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!