Search code examples
c#entity-frameworknavigation-properties

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


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(p);
ctx.SaveChanges();

How can I do that without going to DB ?


Solution

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