2017-04-26 140 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'。'' –