实体框架5:正确的方法,以取代在上下文中的条目 [英] Entity Framework 5 : Proper method to replace entry in context
问题描述
我想要做的是简单的。 我有部分在DB的名单,我想删除/插入/更新它们根据更新列表。
主要的问题是,当我想更换一个条目我不能将其连接到上下文,因为旧的(待更新)项已连接(由previous读取调用)和一个例外是抛出。
我来到身边有3个想法。
- 手动拆下旧条目并附加了新的(虽然改变实体状态到分离仍抛出异常)
- 手动用新的改变旧项的值
- 请读调用非轨道能(AsNoTracking()),这似乎做工精细,但我担心对lazyloading影响。
有没有想任何功能context.entry.replace(oldEntry,newEntry)或其他任何适当的方式做到这一点?
的IEnumerable< SoldPart>老= db.SoldParts.Where(SP => sp.sessionId ==的sessionId);
VAR toDelete = old.Where(PO =>!parts.Any(PU => pu.id == po.id));
VAR toCreate = parts.Where(PO =>!old.Any(PU => pu.id == po.id));
VAR更新所使用= parts.Where(PO => old.Any(PU => pu.id == po.id));
的foreach(在toDelete SoldPart项)
{
db.SoldParts.Attach(项目);
db.SoldParts.Remove(项目);
}
的foreach(在toCreate SoldPart项)
{
db.SoldParts.Add(项目);
}
的foreach(在更新所SoldPart项)
{
db.SoldParts.Attach(项目);
db.Entry(项目).State = EntityState.Modified;
}
db.SaveChanges();
有自动的方式来更新由独立一头连着实体的值,但它仅适用于标/复杂性。没有导航属性:
deb.Entry(oldEntry).CurrentValues.SetValues(newEntry);
What i want to do is simple. I have a list of parts in the db, and i want to delete/insert/update them according to an update list.
The main issue is that, when i want to replace an entry i can't attach it to the context because the older(to be updated) entry is already attached (by previous read call) and an exception is thrown.
I came around with 3 thoughts.
- Manually Detach the old entry and attach the new one (although changing entity state to detached still throws exception)
- Manually change the values of the old entry with the new ones
- Make the read call non track able (AsNoTracking()), this seems to work fine but i am concerned about impact on lazyloading.
Is there any functionality like "context.entry.replace(oldEntry,newEntry)" or any other proper way to do this?
IEnumerable<SoldPart> old = db.SoldParts.Where(sp=>sp.sessionId == sessionId);
var toDelete = old.Where(po=> !parts.Any(pu=>pu.id == po.id));
var toCreate = parts.Where(po => !old.Any(pu => pu.id == po.id));
var toUpdate = parts.Where(po => old.Any(pu => pu.id == po.id));
foreach (SoldPart item in toDelete)
{
db.SoldParts.Attach(item);
db.SoldParts.Remove(item);
}
foreach (SoldPart item in toCreate)
{
db.SoldParts.Add(item);
}
foreach (SoldPart item in toUpdate)
{
db.SoldParts.Attach(item);
db.Entry(item).State = EntityState.Modified;
}
db.SaveChanges();
There is automatic way to update attached entity's values from detached one but it works only on scalar / complex properties. Not on navigation properties:
deb.Entry(oldEntry).CurrentValues.SetValues(newEntry);
这篇关于实体框架5:正确的方法,以取代在上下文中的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!