1

I have two tables:

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

I am using the following EF6 code to add a new adminTest (with its adminTestQuestions) to the database:

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

I have similar but more complicated code to deal with the case where questions are added or removed from the adminTest. All my code works but it would be very good if EF was able to do what I needed rather than my having to add many lines of code.

Can anyone tell me if there have been any changes to EF6 or if any changes are planned to EF7 that will allow it

4

1 回答 1

-1

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

但目前尚不清楚它是否会成为实体中儿童收集的常见事物。 Git hub 实体框架设计会议笔记

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

假设 db 是一个 DbContext

你可以使用这个->:通过反射访问集合

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

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

有些人已经实现了你的解决方案:自动更新已分离实体图

于 2014-10-03T13:43:48.013 回答