简体   繁体   English

实体框架将主键定义为另一个实体的外键

[英]Entity Framework define primary key as foreign key to another entity

I have read some answers but doesn't figure out my case ... 我已经阅读了一些答案,但不知道我的案情...

Let's say I have a BaseEntity class like this: 假设我有一个像这样的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; }
}

And all my entities derive from this: 我所有的实体都来自于此:

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

So, when I try to create an entity, to have its primary key as another entity, I get an error 因此,当我尝试创建一个实体,使其主键作为另一个实体时,出现错误

EntityType 'X' has no key defined. EntityType'X'没有定义键。 Define the key for this EntityType. 定义此EntityType的键。

My code: 我的代码:

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

What am I doing wrong? 我究竟做错了什么?

Why is this kind of relation not accepted? 为什么这种关系不被接受?

If you want that PK also will be FK to another entity, you should do this: 如果您希望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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM