[英]Entity Framework Core relationship tracking
我在Product和Category之間有一個0對多的關系,配置如下:
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; }
}
當我嘗試操作數據(並保存)時, 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
這種行為正確嗎? 因為我預計,一旦進入跟蹤器, CategoryId
字段將在更新Category
字段時更新......
我錯了還是我做錯了什么? 我在文檔中找不到關於此的任何內容...
提前致謝
這是正確的行為。 實體僅在 SaveChanges 之后更新。
但是如果您需要立即更新 CategoryId
product1.CategoryId = cat2.Id;
這是一種更好的更新方式。 有時您需要在此之后,在 SaveChanges 之前添加:
Context.Entry(product1).State = EntityState.Modified;
順便說一句,要獲得 0 對多,您必須修復您的類別 class
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.