gpt4 book ai didi

c# - EF Core 3.1 如何在多对多关系中自动映射

转载 作者:行者123 更新时间:2023-12-04 13:16:09 26 4
gpt4 key购买 nike

我已经在 .NET Core Entity 框架中使用 DB First 方法构建了一个数据库模型。我的数据库中有几个多对多关系,它们都用连接表表示。

像这样:

public partial class Test1
{
public Test1()
{
Test1_Test2= new HashSet<Test1_Test2>();
}

public int Id { get; set; }
..

public virtual ICollection<Test1_Test2> Test1_Test2{ get; set; }
}
public partial class Test2
{
public Test2()
{
Test1_Test2= new HashSet<Test1_Test2>();
}

public int Id { get; set; }
..

public virtual ICollection<Test1_Test2> Test1_Test2{ get; set; }
}
public partial class Test1_Test2
{
public int Test1Id{ get; set; }
public int Test2Id{ get; set; }

public virtual Test1 Test1{ get; set; }
public virtual Test2 Test2{ get; set; }
}

EF 构建了支持这种结构的 Fluent API,在连接表中带有外键和复合主键。

当我要在这种关系中添加一些东西时,这是一种乏味的操作,我必须按照这个思路做一些事情,以便正确填充我的连接表:
_context.Test1.Add(Test1);
_context.Test2.Add(Test2);
Test1_Test2.Test1 = Test1;
Test1_Test2.Test2 = Test2;
_context.Test1_Test2.Add(Test1_Test2);
_context.SaveChanges();

从 .NET Framework 中的旧 EF 中,我记得做一个自动映射器功能很简单,这将使我只能执行以下操作:
Test1.Test2 = Test2; 
_context.Test1.Add(Test1);
_context.SaveChanges();

这很方便,因为 EF 计算出如何自动填充连接表。当我必须从这些表中提出请求时,这也更加方便。

因此,我如何首先在 .Net Core EF DB 中添加“自动映射器”功能 - 这甚至支持吗?

最佳答案

在 EF Core 3 中不支持多对多:

Many-to-many

Many-to-many relationships without an entity class to represent thejoin table are not yet supported. However, you can represent amany-to-many relationship by including an entity class for the jointable and mapping two separate one-to-many relationships.


Relationships (EF Core Docs)
作为部分解决方法,您可以添加 NotMapped属性或遍历这两种关系的函数。您不能编写涉及 NotMapped 属性的查询。
但它们在 EF Core 5 中: Relationships - EF Core - Many-to-many

关于c# - EF Core 3.1 如何在多对多关系中自动映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60322569/

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