c# - 自定义setter添加多对多关系.net core

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

我有三个表,它们组合起来代表多对多关系。即两个表和一个连接表。

这在代码中表示如下:

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; }
    [NotMapped]
    public ICollection<Test2s> Test2
    {
        get => Test1_Test2.Select(r => r.Test2).ToList();
        set => Test1_Test2 = value.Select(v => new Test1_Test2()
        {
            Test2Id = v.Id
        }).ToList();
    }
}

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; }
}

正如您在 Test1 的模型中看到的,我添加了一个“非映射”实体,用于分别获取 Test2 的对象,而无需通过连接表,并添加一个连接表中 Test1 和 Test2 中两个实体之间的关系。

在这里,我已经成功地使用 getter 获取了我的 Test2 对象,如下所示:

var variable = _context.Test1.Include(x => x.Test1_Test2).ThenInclude(x => x.Test2).Where(c => c.Id == Test1.Id);

不幸的是,当我尝试通过setter在连接表“Test1_Test2”中添加关系时,什么也没有发生,这是我的方法:

test1variable.Test2s.Add(test);
_context.Test1.Update(test1variable);
_context.SaveChanges();

我是否错误地使用了我的 setter ,或者是否有更“正确”的方法?

最佳答案

我相信在 setter 中覆盖 ICollection 会破坏 EF.Core 中的更改跟踪:它只跟踪原始的 ICollection 对象,而不是新分配的对象。

相反,尝试在跟踪的集合中删除/添加项目而不分配新列表。 This answer提供了一个具有合适扩展方法的示例,该方法应该实现与您尝试使用自定义属性实现的功能非常相似的功能。

关于c# - 自定义setter添加多对多关系.net core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60328467/

相关文章:

c# - XUnit 测试 DbContext 没有处理

.net - 类似于 VS 2010 Ultimate 的依赖关系图?

.net - .NET 对象创建是 "ex nihilo"吗?

.net - Windows 8.1 无法安装 .NET Framework 3.5 0*800F0906

c# - MVC5 EF6 种子方法 : Cannot insert NULL into column 'Id' table AspNetUsers

c# - TryParse 无故返回 false

c# - OWIN 托管的 web api : using windows authentication and allow anonymous access

c# - 如何使用 C# 在 XML 文件中写入符号 "<" ">"

.net - 通过 LINQ 查询绑定(bind)到 GridView 无法访问部分类属性

c# - 如何防止 Entity Framework 强制验证子对象属性?