实体框架核心多对多解决歧义



通过注释或流畅配置来解决指向同一实体的多对多关系的模糊性的有效方法是什么?给定的模型如:

public class Team
{
public int TeamId { get; set; }
public string Name { get; set; }
// Teams can be owned by multiple users
public List<User> Owners { get; set; }
// Teams can have multiple members
public List<User> Members { get; set; }
}
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
// User can own zero to many teams
public List<Team> Owners { get; set; }
// User can be a member of zero to many teams
public List<Team> Members { get; set; }
}

脚手架导致沿着";无法通过导航确定关系";Team.Owners";类型为";列表";。

这是可以通过手动创建连接实体(如TeamOwnerTeamMember(来有效解决的问题吗?还是EF Core仍在与模糊性作斗争?

感谢您提供的任何帮助。

每个实体上都有两个Navigation属性,EF没有一个约定来标识哪个与哪个匹配。因此,您需要将模型配置为显式关联导航属性。您还需要为链接表选择一个描述性名称。例如:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

modelBuilder.Entity<Team>()
.HasMany(t => t.Owners)
.WithMany(o => o.OwnerOf)
.UsingEntity(j => j.ToTable("TeamOwners"));
modelBuilder.Entity<Team>()
.HasMany(t => t.Members)
.WithMany(o => o.MemberOf)
.UsingEntity(j => j.ToTable("TeamMembers"));

base.OnModelCreating(modelBuilder);
}

您可以将导航属性与注释关联起来,但不能命名链接表。例如

public class Team
{
public int TeamId { get; set; }
public string Name { get; set; }
[InverseProperty(nameof(User.OwnerOf))]
public List<User> Owners { get; set; }
[InverseProperty(nameof(User.MemberOf))]
public List<User> Members { get; set; }
}

相关内容

  • 没有找到相关文章

最新更新