簡體   English   中英

實體框架更新:存儲更新,插入或刪除語句影響了意外的行數

[英]Entity Framework On Update : Store update, insert, or delete statement affected an unexpected number of rows

我有以下型號:-

    public abstract class BaseClass
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public Guid Id
            {
                get;
                set;
            }protected BaseClass()
            {
                if (Guid.Empty==Id)
                {
                    Id = LongGuid.NewGuid();

                }
            }
        }
    }

    public class Product : BaseClass
        {

          // other properties like name and price.
          private Recipe _recipe;
            public virtual Recipe Recipe
            {
                get
                {    
                    return this._recipe;
                }
                set
                {
                    this._recipe = value;
                }
            }

            private InventoryItem _inventoryItem;
            public virtual InventoryItem InventoryItem
            {
                get
                {
                    return this._inventoryItem;
                }
                set
                {
                    this._inventoryItem = value;
                }
            }
public class InventoryItem  : BaseClass
{
 // Name and value 
}

public class Recipe : BaseClass
{
 // Name and value 
}
public class DataContext : DbContext
{
    public DbSet<Recipe> Recipes { get; set; }
    public DbSet<InventoryItem> InventoryItems { get; set; }
    public DbSet<Product> Product { get; set; }
}

我保存如下:

this._workspace.Update(Model);
this._context.SaveChanges();

當我使用InventoryItem和Recipe創建產品時,它的效果很好。

但是當我創建沒有InventoryItem和Recipe的產品並保存在數據庫中后,有時我嘗試使用新的InventoryItem()和新的Recipe()更新產品,但出現以下錯誤:-

保存不公開外鍵屬性為其關系的實體時發生錯誤。 EntityEntries屬性將返回null,因為無法將單個實體標識為異常的來源。 通過在實體類型中公開外鍵屬性,可以簡化保存時的異常處理。 有關詳細信息,請參見InnerException。

內部錯誤:-

存儲更新,插入或刪除語句影響了意外的行數(0)。 自加載實體以來,實體可能已被修改或刪除。 有關了解和處理樂觀並發異常的信息,請參見http://go.microsoft.com/fwlink/?LinkId=472540

您收到此錯誤的原因是因為EF無法確定如何將您的產品與Recipe和InventoryItem相關聯。 要解決此問題,請暫時刪除您的InventoryItem,並使您的產品和配方按預期保留。

使用EF 6和Core,您可以選擇在父實體中定義FK字段,並將其命名為所引用的子實體的FK。

例如,使用代碼優先注釋:

public class Product
{
   [Key]
   public Guid ProductId {get; set;}

   [ForeignKey("RecipeId")]
   public virtual Recipe Recipe {get; set;}

   public Guid RecipeId {get; set;}

   // ...
}

或者,您可以通過實體類型配置使用配置,也可以使用.HasForeignKey()fluent方法覆蓋DbContext的OnModelCreating來建立外鍵。

如果您不小心,則以這種方式映射FK會引發問題,因為您現在擁有對Recipe實體的引用以及單獨的FK引用,並且必須確保它們保持同步。

另外,在EF 6中,您可以在實體類型配置或DbContext的OnModelCreating中使用.Map()/ w .MapKey()聲明FK的列,而無需聲明屬性。 根據我對EF Core的了解,這不是一個選擇。

一旦您使用了配方參考,InventoryItem的參考將是相同的。

我在這篇文章中略述了使用引用vs.FK(而不是兩者)的問題: http : //www.practicagility.com.au/2017/10/27/ef-a-1st-class-citizen-part- 4-使用引用-VS-鍵/

暫無
暫無

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

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