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

标签 c# entity-framework asp.net-core

我已经在 .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 the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table 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/

相关文章:

asp.net-core - StackExchange.Redis.StrongName 被引用但不包含在包中

c# - Devexpress ASPxDateEdit 控件 OnDateChanged 事件未触发

c# - NLog:如何控制 LogEventInfo 对象的消息格式?

c# - 初始化字符串的格式不符合从索引 165 开始的规范

c# - 具有多个可选一对一关系的 Entity Framework 表

c# - C# WebAPI Controller /服务/存储库中 Controller 级别的错误/异常处理

c# - 将 Json 对象反序列化为 C# 对象不起作用

c# - 当存储的数据类型发生变化时,如何升级 Settings.settings?

c# - Entity Framework 选择上个月记录

c# - 无法在 .net 核心中使用 WCF WSHttpBinding