【问题标题】:EF Core 3.1 how to automap in Many-to-many relationshipEF Core 3.1 如何在多对多关系中自动映射
【发布时间】:2020-02-20 14:48:24
【问题描述】:

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

像这样:

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 中添加“自动映射器”功能 - 这甚至受支持吗?

【问题讨论】:

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


    【解决方案1】:

    在 EF Core 3 中不支持多对多。这是来自旧文档:

    多对多

    没有实体类来表示的多对多关系 尚不支持连接表。但是,您可以代表一个 通过包含连接的实体类来实现多对多关系 表和映射两个单独的一对多关系。

    作为部分解决方法,您可以添加NotMapped 属性或遍历这两种关系的函数。您不能编写涉及 NotMapped 属性的查询。

    但它们存在于 EF Core 5 中:Relationships - EF Core - Many-to-many

    【讨论】:

    猜你喜欢
    • 2018-07-03
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    相关资源
    最近更新 更多