【发布时间】:2015-12-17 17:28:06
【问题描述】:
我对实体框架和代码优先迁移有点陌生,所以我希望这是一个容易回答的问题。我正在尝试在 ApplicationUser(来自 ASP.NET 身份)和成员之间创建一对一的关系。我有一个会员类:
public class Member
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Address Address { get; set; }
public UserStatus Status { get; set; }
public DateTime CreateDate { get; set; }
public virtual string ApplicationUserID { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
还有一个 ApplicationUserClass:
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
}
public virtual Member Member { get; set; }
}
在我的 DBContext(继承 IdentityDbContext)中,我有以下配置:
modelBuilder.Entity<ApplicationUser>()
.HasOptional(t => t.Member).WithOptionalPrincipal();
base.OnModelCreating(modelBuilder);
当我运行代码第一次迁移时,我得到了这个:
CreateTable(
"dbo.Members",
c => new
{
ID = c.Int(nullable: false, identity: true),
FirstName = c.String(),
LastName = c.String(),
Status = c.Int(nullable: false),
CreateDate = c.DateTime(nullable: false),
ApplicationUserID = c.String(maxLength: 128),
Address_ID = c.Int(),
ApplicationUser_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Addresses", t => t.Address_ID)
.ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id)
.ForeignKey("dbo.AspNetUsers", t => t.ApplicationUserID)
.Index(t => t.ApplicationUserID)
.Index(t => t.Address_ID)
.Index(t => t.ApplicationUser_Id);
请注意,我有 2 个外键,ApplicationUserID 和 ApplicationUser_Id。我想尝试使用 FluentAPI 做所有事情(即不是数据注释)。我将如何配置它以使 EF 使用 ApplicationUserID,即我在课堂上拥有的字符串 ID?我以为 Class+ID 是约定俗成的,那为什么还要创建另一个外键呢?
【问题讨论】:
-
您可以将您的 Member 类的 modelBuilder 配置代码添加到您的问题中吗?
标签: c# .net entity-framework ef-code-first