【发布时间】:2016-05-06 06:13:42
【问题描述】:
我在我的项目中使用 ASP.NET Identity,所以我的 AspNetUser 表看起来有点像这样:
public class AspNetUser
{
[Key, Index(IsUnique = true), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Index(IsUnique = true), DatabaseGenerated(DatabaseGeneratedOption.None)]
public int InternalId { get; set; }
// Navigation properties
public virtual ICollection<RequestHistory> RequestHistories { get; set; }
}
我已添加 InternalId 以在我的自定义表中用作外键,因为我不喜欢到处使用 Guid。所以,我们以这张表为例:
public class RequestHistory
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? UserId { get; set; }
// Navigation properties
[ForeignKey("UserId")]
public virtual AspNetUser User { get; set; }
}
到目前为止看起来不错,RequestHistory 应该具有在 RequestHistory.UserId = AspNetUser.InternalId 上运行的 AspNetUser 的导航属性,反之亦然。但是当我尝试运行我的项目时,我收到一条错误消息:
RequestHistory_User_Target_RequestHistory_User_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'UserId' on entity 'RequestHistory' does not match the type of property 'Id' on entity 'AspNetUser' in the referential constraint 'RequestHistory_User'.
这是有道理的,因为 EF 可能会尝试使用默认行为来匹配它们,但是我如何强制此关联使用 InternalId 作为 AspNetUser 表中的外键?
【问题讨论】:
-
请查看 Stack Overflow 上的以下问题stackoverflow.com/questions/27609023/…
-
谢谢你的回答,但你是不是暗示因为
The Entity Framework currently only supports basing referential constraints on primary keys所以不能做?
标签: c# entity-framework ef-code-first entity-framework-6