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

2019-06-06 02:32发布

问题:

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