【问题标题】:Has EF6+ / 7 added any ways that I can add update child tables?EF6+ / 7 添加了我可以添加更新子表的任何方式吗?
【发布时间】:2014-11-22 05:41:42
【问题描述】:

我有两张桌子:

    public AdminTest()
    {
        this.AdminTestQuestions = new List<AdminTestQuestion>();
    }
    public int AdminTestId { get; set; }
    public string Title { get; set; }     
    public virtual ICollection<AdminTestQuestion> AdminTestQuestions { get; set; }
}

public partial class AdminTestQuestion
{
    public int AdminTestQuestionId { get; set; }
    public int AdminTestId { get; set; }
    public System.Guid QuestionUId { get; set; }
    public virtual AdminTest AdminTest { get; set; }
}

我正在使用以下 EF6 代码将新的 adminTest(及其 adminTestQuestions)添加到 数据库:

    public async Task<IHttpActionResult> Post([FromBody]AdminTest adminTest)
    {
        db.AdminTests.Add(adminTest);
        foreach (AdminTestQuestion adminTestQuestion in adminTest.AdminTestQuestions) 
        {
            db.AdminTestQuestions.Add(adminTestQuestion);
        }
        await db.SaveChangesAsync(User, DateTime.UtcNow);
        return Ok(adminTest);
    }

我有类似但更复杂的代码来处理在 adminTest 中添加或删除问题的情况。我所有的代码都可以工作,但如果 EF 能够做我需要的事情,而不是我必须添加很多代码行,那就太好了。

谁能告诉我 EF6 是否有任何更改,或者是否计划对 EF7 进行任何更改以允许它

【问题讨论】:

标签: sql-server entity-framework entity-framework-6 entity-framework-core


【解决方案1】:

在 ef7 github 上已经注意到,他们接缝添加了一些添加主键实体的简洁代码。

但目前尚不清楚它是否会成为实体中的子集合的常见事物。 Git hub Entity Framework Design Meeting Notes

但对于 EF6,您可以使用通用存储库为您完成所有工作。 (因为不能直接扩展 DbContext)

假设 db 是一个 DbContext

你可以使用这个 -> :Accessing a Collection Through Reflection

然后从包含 ICollection 的类 T 中找到所有属性,并对 ICollection 属性的项目执行 foreach,然后对其执行 db.Set.Add(proprietyChild)

这将消除总是重复相同的添加子实体代码的需要。

有些人已经实现了你的解决方案:Automated updates of a graph of deached entities

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    相关资源
    最近更新 更多