Note that there are some explanatory texts on larger screens.

plurals
  1. POEF 5.0 Foreign Key Not Updating
    primarykey
    data
    text
    <p>I know there are some other questions regarding this-- but I was unable to get them to solve my problem.</p> <p>I have the following classes:</p> <pre><code>public class Category { public Category() { Products = new List&lt;Product&gt;(); } public int Id { get; set; } public string Name { get; set; } public List&lt;Product&gt; Products { get; set; } public override string ToString() { return String.Format("{0}{1}", Id, Name); } } </code></pre> <p>and</p> <pre><code>public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public Category Category { get; set; } public override string ToString() { return String.Format("{0}{1}", Id, Name); } } </code></pre> <p>I've got some code which attempts to update both a product and it's category:</p> <pre><code> using (var ctx = GetCtx()) { var beverages = new Category {Id = 1 }; var milk = new Product { Name = "MILK", Id = 4, Category = new Category { Id = 1} }; ctx.Entry(milk).State = System.Data.EntityState.Modified; ctx.SaveChanges(); } </code></pre> <p>this results in the following sql statement:</p> <pre><code>update [dbo].[Products] set [Name] = @0, [Price] = @1 where ([Id] = @2) @0: MILK @1: 0 @2: 4 </code></pre> <p>I can't figure out how to make sure that the Category for the particular product is updated. I thought about adding a property to Product for Category_Id but this results in an additional column being generated in my database.</p> <p>EDIT: I think I figured this out-- after watching Julia Lerman's series on EF (Pluralsight)-- the way to set up this class is like this:</p> <pre><code>public class Product { public int Id { get; set; } [Required] [MaxLength(200)] public string Name { get; set; } public virtual Category Category { get; set; } public int CategoryId { get; set; } } </code></pre> <p>This results in only one foreign key column in the Products table. The Category of the Product gets updated when updating the CategoryId property.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload