2017-09-25 44 views
0

在C#中使用EF6: - 我有模型A,裏面有模型B和C.存儲更新,插入或刪除語句影響了意想不到的行數

class A 
{ 
    Guid Id; 
    B b; 
    C c; 

    public A() 
    { 
     Id = new Guid; 
    } 
} 

class B 
{ 
    Guid Id; 

    public B() 
    { 
     Id = new Guid; 
    } 
} 

當模型A保存在數據庫(沒有B和C)它的工作正常。當我從數據庫中獲取它,然後創建新的B並將其分配給A並嘗試保存它。獲取錯誤

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

保存不會爲其關係公開外鍵 屬性的實體時發生錯誤。 EntityEntries屬性 將返回null,因爲無法將單個實體標識爲異常的源 。通過在您的實體類型中公開外鍵屬性,可以更輕鬆地處理異常,同時保存 。有關詳細信息,請參閱 InnerException。

(我把所有的鍵都作爲GUID)。 在進一步的調試我可以看到EntityKey爲B在異常空。 enter image description here

我累了這link1,link2但這個解決方案的非工作。

+0

取'A'用''B'包括()'-ed。 –

回答

0

首先,我會使用屬性,而不是字段。

然後,我看到你有AB也是之間AC其中BC是可選之間一比一的關係。

「當配置一個一對一的關係, 實體框架要求相關的主鍵也成爲 外鍵。」 - 由朱莉婭·勒曼&羅文米勒

編程實體框架代碼優先所以另一個問題是,在課堂上B您通過構造方法設置Id值。

我會嘗試下面這個樣子:

using System; 
using System.ComponentModel.DataAnnotations; 
using System.ComponentModel.DataAnnotations.Schema; 

namespace EFExposeForeignKey 
{ 
    public class A 
    { 
     public A() 
     { 
      Id = Guid.NewGuid(); 
     } 

     [Key] 
     public Guid Id { get; set; } 

     /* Other properties of A goes here */ 

     // Navigation property 
     public B B { get; set; } 

     // Navigation property 
     public C C { get; set; } 
    } 

    public class B 
    { 
     [Key] 
     [ForeignKey(nameof(EFExposeForeignKey.A.B))] 
     // Or simply [ForeignKey("B")] 
     // I wanted to emphasize here that "B" is NOT the type name but the name of a property in class "A" 
     public Guid Id { get; set; } 

     /* Other properties of B goes here */ 

     // Navigation property 
     public A A { get; set; } 
    } 

    public class C 
    { 
     [Key] 
     [ForeignKey(nameof(EFExposeForeignKey.A.C))] 
     public Guid Id { get; set; } 

     /* Other properties of C goes here */ 

     // Navigation property 
     public A A { get; set; } 
    } 
} 
相關問題