开发者

Entity Model - How to insert / update data which involves navigational properties

开发者 https://www.devze.com 2023-03-22 12:18 出处:网络
I am using Entity Framework, WebForms, .Net Framework 3.5 I want to update a record in database using entity model which involves updating a foreign key too, which has become a navigational property i

I am using Entity Framework, WebForms, .Net Framework 3.5 I want to update a record in database using entity model which involves updating a foreign key too, which has become a navigational property in Entity.

How can I do that? I have seen a way which involves another query like

Product p = new Product{
   ID = 5,
   Name = "Bovril",
   Category = ctx.Categories.First( c => c.ID == 5)
};
ctx.AddToProducts开发者_Python百科(p);
ctx.SaveChanges();

How can I do that without going to DB ?


Try this (this works with EF 4 so hopefully it will work with EF 1 as well):

Category c = new Category 
{
    ID = 5
};
ctx.AttachTo("Categories", c);

Product p = new Product
{
   ID = 5,
   Name = "Bovril"
};
ctx.AddToProducts(p);

p.Category = c;
ctx.SaveChanges();
0

精彩评论

暂无评论...
验证码 换一张
取 消