在我的 EF6 Code First 模型中,我有以下类:
class User : IdentityUser // so it has public string Id!
{
public virtual long ItemId { get; set; }
public virtual Item Item { get; set; }
}
class Item
{
public virtual long Id { get; set;
public virtual string UserId { get; set; }
public virtual User User { get; set; }
}
在我的上下文中,我执行以下操作:
OnModelCreating(DbModelBuilder mB)
{
mB.Entity<User>().HasOptional(x => x.Item).WithOptionalPrincipal(x => x.User).WillCascadeOnDelete(false);
}
但是,我的迁移产生以下内容:
CreateTable(
"dbo.Items",
c => new
{
Id = c.Long(nullable: false, identity: true),
UserId = c.String(),
User_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.User_Id)
.Index(t => t.User_Id);
我忘了做什么?
更新:我也尝试添加[ForeignKey("User")]
到Item.UserId
Update2:我找到了一种解决方法,但它不是很漂亮......
OnModelCreating(DbModelBuilder mB)
{
mB.Entity<User>().HasOptional(x => x.Item).WithMany().HasForeignKey(x => x.ItemId);
mB.Entity<Item>().HasOptional(x => x.User).WithMany().HasForeignKey(x => x.UserId);
}