简体   繁体   中英

Entity Framework Core relationship tracking

I have a 0-to-many relationship between Product and Category, configured as follows:

public class Product 
{

    public int Id { get; set; }
    public string Name { get; set; }
   
    public int? CategoryId { get; set; }
    public Category Category { get;set; }
}

public class Category
{
     public int Id { get; set; }
     public string Name { get; set; }
}

When I try to manipulate data (and save), I have a strange behaviour with the CategoryId

// ...

var cat1 = this.Context.Categories.Find(1);
var cat2 = this.Context.Categories.Find(2);

var product1 = new Product();
product1.Name = "Test";
product1.Category = cat1;  // the CategoryId property is NOT set

this.Context.Products.Add(product1);  // the CategoryId property is set
this.Context.SaveChanges();

product1.Category = cat2;  // the CategoryId property is NOT updated

this.Context.SaveChanges();  // the CategoryId property is updated

Is this behaviour correct? Because I would have expected that, once in tracker, the CategoryId field to be updated when the Category field is updated...

Am I wrong or am I doing something wrong? I cannot find anything in the docs about this...

Thanks in advance

This is the correct behavior. Entity is updated only after SaveChanges.

But if you need to update CategoryId immediately

product1.CategoryId = cat2.Id;

and it is a better way to update. Sometimes you will need to add after this, before SaveChanges:

Context.Entry(product1).State = EntityState.Modified;

And by the way, to get 0-to-many you have to fix your Category class

public class Category
{
     public int Id { get; set; }
     public string Name { get; set; }
      public virtual ICollection<Product> Products { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM