2017-04-26 151 views
0

我看過一些答案,但沒有弄清楚我的情況......實體框架定義主鍵外鍵到另一個實體

比方說,我有一個BaseEntity類是這樣的:

public abstract class BaseEntity<TKey> : IEntity<TKey> 
{ 
    /// <summary> 
    /// Gets or sets the key for all the entities 
    /// </summary> 
    [Key] 
    public TKey Id { get; set; } 
} 

和我所有的實體源於此:

public class A : BaseEntity<Guid> { 
    // ...props 
} 

所以,當我嘗試創建一個實體,有其主鍵另一個實體,我得到一個錯誤

EntityType 'X' has no key defined. Define the key for this EntityType.

我的代碼:

public class X : BaseEntity<A> { // <-- doesn't accept it 
    // ...props 
} 

我在做什麼錯?

爲什麼這種關係不被接受?

回答

0

如果您想獲得PK也將是FK到另一個實體,你應該這樣做:

public abstract class BaseEntity<TKey> : IEntity<TKey> 
{ 
    //[Key] attribute is not needed, because of name convention 
    public virtual TKey Id { get; set; } 
} 

public class X : BaseEntity<Guid>//where TKey(Guid) is PK of A class 
{ 
    [ForeignKey("a")] 
    public override Guid Id { get; set; } 
    public virtual A a { get; set; } 
} 
+0

泰,它幫了我很多....只是有些事......它不會忽略它新。在類X中需要* [Key] *,否則我們會發生此錯誤: >'在模型生成過程中檢測到一個或多個驗證錯誤:X_A_Source::多重性在角色'X_A_Source'中的關係' X_A」。因爲依賴角色是指關鍵屬性,所以依賴角色的多重性的上界必須是'1'。'' –