很简单,我首先使用的是Entity Framework 4.1代码,我想用modelBuilder上的Fluent调用替换我的[ForeignKey(..)]属性。类似于下面的WithRequired(..)和HasForeignKey(..)的东西,它将显式外键属性(CreatedBySessionId)与关联的导航属性(CreatedBySession)绑定在一起。但我想这样做是为了一对一的关系而不是一对一:
modelBuilder.Entity<..>().HasMany(..).WithRequired(x => x.CreatedBySession).HasForeignKey(x => x.CreatedBySessionId)
下面是一个更具体的例子。这与[ForeignKey(..)]属性非常愉快,但我想废除它并纯粹在模型构建器上配置它。
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
}
}
此处会话可以负责创建许多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"));
感觉我错过了一些非常明显的东西,因为我想要做的就是执行与[ForeignKey(..)]相同的操作,但是在模型构建器中。或者这是一种不好的做法并被明确排除在外的情况?
答案 0 :(得分:10)
您需要将关系映射为一对多,并省略关系中的集合属性。
modelBuilder.Entity<Session>()
.HasOptional(x => x.CurrentApplication)
.WithMany()
.HasForeignKey(x => x.CurrentApplicationId)