gpt4 book ai didi

many-to-many - 如何让 EF 4.1 RC 代码优先使用正确的外键?

转载 作者:行者123 更新时间:2023-12-04 04:45:20 25 4
gpt4 key购买 nike

我使用的是 CTP5,然后切换到 RC1。在不更改 EntityTypeConfiguration 的情况下,EF 现在正尝试通过错误的列名查找内容。它使用的是列名的单数而不是复数,我不知道它是从哪里得到这个想法的。

示例:多对多

//User.Roles
//Role.Users

//User EntityTypeConfiguration

this.HasKey(x => x.Id);

this.HasMany(x => x.Roles)
.WithMany().Map(m => {
m.MapLeftKey("Users_Id");
m.MapRightKey("Roles_Id");
m.ToTable("UserRoleLinks");
});

然后我得到错误:

列名称“User_Id”无效。

它从哪里获得“User_Id”?表Id为“Id”;连接表明确表示为“Users_Id” CTP5 和 RC1 之间发生了什么变化会导致这种情况?

更新:

我正在使用“modelBuilder.Conventions.Remove ()”是否不再受支持?这可能是问题所在吗?我不确定现在的默认行为是什么。

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();

modelBuilder.Configurations.Add(new UserConfig());
}

最佳答案

我发现我做错了什么。简短的回答是我需要定义多对多关系的双方,因为每个类都参与了一个互惠集合(User.Roles 和 Role.Users)。显然,对于 CTP5,这不是必需的。

参见:Many to Many mapping not working - EF 4.1 RC

为了坚持我的例子,这是正确的语法。

this.HasMany(x => x.Roles)
.WithMany(r => r.Users).Map(m => {
m.MapLeftKey("Users_Id");
m.MapRightKey("Roles_Id");
m.ToTable("UserRoleLinks");
});

有几个陷阱使我难以理解简单的解决方案。

1) 只定义一次关系。我在不同的 EntityTypeConfiguration 类中从两个角度定义多对多关系,这是没有必要的,而且会带来自己的错误。

2) 不要混淆用于 MapLeftKey 和 MapRightKey 的字段。该顺序很直观,但我猜它很容易通过复制/粘贴等方式混淆。

关于many-to-many - 如何让 EF 4.1 RC 代码优先使用正确的外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5557054/

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