Entity Framework 将主键定义为另一个实体的外键
Entity Framework define primary key as foreign key to another entity
我已经阅读了一些答案,但没有弄清楚我的情况...
假设我有这样一个 BaseEntity
class:
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
}
我做错了什么?
为什么这种关系不被接受?
如果你希望 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; }
}
我已经阅读了一些答案,但没有弄清楚我的情况...
假设我有这样一个 BaseEntity
class:
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
}
我做错了什么?
为什么这种关系不被接受?
如果你希望 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; }
}