我有一个表格 带有定义的故事
public class Tale
{
public int Id { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public DateTime ReleaseDate { get; set; }
public int enum_TaleAuthorTypeId { get; set; }
public virtual enum_TaleAuthorType enum_TaleAuthorType { get; set; }
public int CommentableId { get; set; }
public virtual Commentable Commentable { get; set; }
}
当我在控制台中键入"更新数据库"时,我与 CommentableId 的一列和enum_TaleAuthorTypeId的一列有着良好的关系。
现在,我想添加用户配置文件并尝试键入以下内容:
public int UserProfileId { get; set; }
public virtual UserProfile UserProfile { get; set; }
但是在添加迁移之后,我有这个:
AddColumn("dbo.Tales", "UserProfileId", c => c.Int(nullable: false));
AddColumn("dbo.Tales", "UserProfile_UserId", c => c.Int());
我应该如何只获得一列值?为什么要创建两列?
问题是,按照惯例,EF 希望UserProfile
的主键是Id
的,但你将其作为UserId
。
可以将 UserId
in UserProfile
的属性名称更改为 Id
,以便 EF 按约定推断密钥,也可以重写约定并将UserId
保留为主键。
您可以使用属性覆盖约定,例如
[ForeignKey("UserProfileId")]
public virtual UserProfile UserProfile { get; set; }
或使用 Fluent API,例如
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Tale>()
.HasRequired(a => a.UserProfile)
.WithMany()
.HasForeignKey(u => u.UserProfileId);
}