簡體   English   中英

實體框架和多對多映射:更新問題

[英]Entity Framework and Many-To-Many mapping: update issue

我在模型中映射了多對多關系。 材質實體與許多顏色實體相關,反之亦然。 我為此使用了中間表( MaterialColor ),該表只有兩個id列,它們引用每個表中的每個id。

這是在我的DbContext實現中進行配置的方式

       modelBuilder.Entity<Material>().HasMany<Color>(p => p.Colors).WithMany()
           .Map(m =>
           {
               m.ToTable("MaterialColor");
               m.MapLeftKey("MaterialId");
               m.MapRightKey("ColorId");
           });

到目前為止,這還不是問題:除了現在我還通過實體Printer將另一個多對多關系映射到Material:映射的配置方式完全相同:

        modelBuilder.Entity<Printer>().HasMany<Material>(p => p.Materials).WithMany()
           .Map(m =>
           {
               m.ToTable("PrinterMaterial");
               m.MapLeftKey("PrinterId");
               m.MapRightKey("MaterialId");
           });

當我嘗試在PrinterMaterial中創建一個Printer實體及其與Material的關系時,就會出現真正的問題,但是我不想插入新的Material或Colors ,當然 不想插入 MaterialColor記錄

我一直在逐步解決此問題,並設法跳過了它在我不想插入的表中的插入:

        _dbContext.Printers.Add(printer);
        foreach (var material in printer.Materials)
        {
            foreach (var color in material.Colors)
            {
                _dbContext.Entry(color).State = EntityState.Unchanged;
            }
            _dbContext.Entry(material).State = EntityState.Unchanged;
        }
        _dbContext.SaveChanges();

該問題尚未完全解決,因為它仍在嘗試插入MaterialColor中 我不確定如何告訴EF也跳過這種關系。

我嘗試了這個:

        _dbContext.Entry(material).Property(m => m.Colors).IsModified = false;

但我收到此錯誤:

附加信息:類型為“材料”的屬性“顏色”不是原始屬性或復雜屬性。 Property方法只能與原始或復雜屬性一起使用。 使用引用或收集方法。

這很有意義,因為“顏色”是一個集合。

我如何告訴EF忽略這種關系?

(PS:不加載沒有顏色的材料是不可行的)

編輯 :添加打印機和printer.Materials初始化:

        var printer = new Printer();
        printer.Materials = new List<Material>();
        printer.Materials.Add(_materialService.GetMaterialById(materialId)); // this gives the material with many properties populated, like Colors.

由於找不到解決方法,因此必須刪除此映射:

       modelBuilder.Entity<Material>().HasMany<Color>(p => p.Colors).WithMany()
       .Map(m =>
       {
           m.ToTable("MaterialColor");
           m.MapLeftKey("MaterialId");
           m.MapRightKey("ColorId");
       });

並使用兩個字段創建實體:

public class MaterialColor : ICacheableEntity
{
    public virtual Material Material { get; set; }
    public virtual Color Color { get; set; }
    public int ColorId { get; set; }
    public int MaterialId { get; set; }
}

這樣,我可以在需要時將Material實體的MaterialColor集合元素設置為Unchanged

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM