有没有EF6 + / 7添加任何方式可以添加更新子表? [英] Has EF6+ / 7 added any ways that I can add update child 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; }
}
我使用以下EF6代码添加一个新的adminTest adminTestQuestions)到
数据库:
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);
}
我有类似但更复杂的代码来处理添加问题的情况或从adminTest中删除。我所有的代码都可以工作,但是如果EF能够做我所需要的,而不是添加许多代码行,那将是非常好的。
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.
任何人都可以告诉我对EF6进行了任何更改,或者如果EF7有任何修改,将允许它更改。
Can anyone tell me if there have been any changes to EF6 or if any changes are planned to EF7 that will allow it
推荐答案
已注意到ef7 github他们接缝添加了一些添加主键实体的整洁的代码。
has noted on the ef7 github they seams to have added some neat code that add primary key entity.
但是,如果这是一个实体中的儿童收藏将是一个常见的事情仍然不清楚。
Git hub实体框架设计会议笔记
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
但对于EF6,您可以使用通用存储库为您做所有工作。 (因为你不能直接扩展DbContext)
but for EF6 you could use a Generic Repository to make all the work for you. (since you can't extend DbContext directly)
假设db是一个DbContext
assuming db is a DbContext
你可以使用这个 - >:通过反思访问集合
you could use this -> : Accessing a Collection Through Reflection
然后从包含ICollection>的类T中查找所有属性,并对ICollection属性的项执行foreach,然后在其上执行db.Set.Add(proprietyChild)
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
这篇关于有没有EF6 + / 7添加任何方式可以添加更新子表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!