EF 4.1 Code First ModelBuilder HasForeignKey用于一对一关系

Wal*_*ter 5 entity-framework one-to-one code-first ef-code-first entity-framework-4.1

很简单,我首先使用Entity Framework 4.1代码,我想用modelBuilder上的流畅调用替换我的[ForeignKey(..)]属性.类似于下面的WithRequired(..)和HasForeignKey(..)的东西,它将显式外键属性(CreatedBySessionId)与关联的导航属性(CreatedBySession)绑定在一起.但我想这样做是为了一对一的关系,而不是一对一:

modelBuilder.Entity<..>().HasMany(..).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId)
Run Code Online (Sandbox Code Playgroud)

下面是一个更具体的例子.这与[ForeignKey(..)]属性非常愉快,但我想废除它并纯粹在modelbuilder上配置它.

public class VendorApplication
{
    public int VendorApplicationId { get; set; }

    public int CreatedBySessionId { get; set; }
    public virtual Session CreatedBySession { get; set; }
}

public class Session
{
    public int SessionId { get; set; }

    [ForeignKey("CurrentApplication")]
    public int? CurrentApplicationId { get; set; }
    public virtual VendorApplication CurrentApplication { get; set; }

    public virtual ICollection<VendorApplication> Applications { get; set; }
}

public class MyDataContext: DbContext
{
    public IDbSet<VendorApplication> Applications { get; set; }
    public IDbSet<Session> Sessions { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Session>().HasMany(x => x.Applications).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId).WillCascadeOnDelete(false); 
        // Note: We have to  turn off Cascade delete on Session <-> VendorApplication relationship so that SQL doesn't complain about cyclic cascading deletes
    }
}
Run Code Online (Sandbox Code Playgroud)

这里,Session可以负责创建许多VendorApplications(Session.Applications),但Session一次最多只能处理一个VendorApplication(Session.CurrentApplication).我想将CurrentApplicationId属性与modelBuilder中的CurrentApplication导航属性绑定,而不是通过[ForeignKey(..)]属性绑定.

我试过的事情

删除[ForeignKey(..)]属性时,CurrentApplication属性会在数据库中生成CurrentApplication_VendorApplicationId列,该列与CurrentApplicationId列无关.

我已尝试使用CurrentApplicationId列名显式映射关系,如下所示,但显然这会生成错误,因为属性Session.CurrentApplicationId已使用数据库列名"CurrentApplicationId":

modelBuilder.Entity<Session>().HasOptional(x => x.CurrentApplication).WithOptionalDependent().Map(config => config.MapKey("CurrentApplicationId"));
Run Code Online (Sandbox Code Playgroud)

感觉就像我在这里遗漏了一些非常明显的东西,因为我想做的就是执行与[ForeignKey(..)]相同的操作,但是在模型构建器中.或者这是一个不好的做法并明确被排除在外的情况?

Era*_*nga 10

您需要将关系映射为一对多,并省略关系中的集合属性.

modelBuilder.Entity<Session>()
   .HasOptional(x => x.CurrentApplication)
   .WithMany()
   .HasForeignKey(x => x.CurrentApplicationId)
Run Code Online (Sandbox Code Playgroud)