gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:47:21 25 4
gpt4 key购买 nike

很简单,我首先使用 Entity Framework 4.1 代码,我想用对模型构建器的流畅调用替换我的 [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
}
}

这里一个 Session 可以负责创建许多 VendorApplications(Session.Applications),但是一个 Session 一次最多只处理一个 VendorApplication(Session.CurrentApplication)。我想将 CurrentApplicationId 属性与模型构建器中的 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(..)] 相同的操作。或者这是一种不好的做法并且被明确排除在外的情况?

最佳答案

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

modelBuilder.Entity<Session>()
.HasOptional(x => x.CurrentApplication)
.WithMany()
.HasForeignKey(x => x.CurrentApplicationId)

关于entity-framework - EF 4.1 Code First ModelBuilder HasForeignKey 用于一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11480083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com