Has EF6+ / 7 added any ways that I can add update child tables?

故事扮演 提交于 2019-12-23 01:59:09

问题


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


回答1:


has noted on the ef7 github they seams to have added some neat code that add primary key entity.

but it is still not clear as to if it will be a common thing for children collection in an entity. Git hub Entity Framework Design Meeting Notes

but for EF6 you could use a Generic Repository to make all the work for you. (since you can't extend DbContext directly)

assuming db is a DbContext

you could use this -> : Accessing a Collection Through Reflection

then find all Property from a class T that contains ICollection<> and do a foreach on the item of the ICollection Property then do db.Set.Add(proprietyChild) on it

that would eliminate the need for always repeating the same add child to entity code.

some people already did implement a solution thou : Automated updates of a graph of deached entities



来源:https://stackoverflow.com/questions/26072646/has-ef6-7-added-any-ways-that-i-can-add-update-child-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!