用一个简单的方法的EntityFramework .NET 4更新实体 [英] EntityFramework .net 4 Update entity with a simple method
问题描述
我一直在寻找这太问题:<一href="http://stackoverflow.com/questions/1168215/ado-net-entity-framework-update-only-certian-properties-on-a-detached-entity">http://stackoverflow.com/questions/1168215/ado-net-entity-framework-update-only-certian-properties-on-a-detached-entity.这对我来说是很大的帮助。我现在,我需要让我的更改之前附加一个实体知道。但如何才能做到这一点:
I was looking at this SO question: http://stackoverflow.com/questions/1168215/ado-net-entity-framework-update-only-certian-properties-on-a-detached-entity. This was a big help for me. I know now that I need to attach an entity before making my changes to it. But how can do I do this:
我有一个MVC网站,客户更新页面与字段:ID,名称,地址,等我的MVC被解析到这一个客户实体。我该怎么做了以下内容:
I have an MVC website, a Customer Update Page with fields: ID, Name, Address, etc. My MVC is parsing this into a Customer entity. How do I do the following:
- 更新我的实体,并保存更改。
- 捕获异常,如果我已经作了修改,因为我装我的实体。
推荐答案
尝试是这样的(伪code,我可能记错一些方法名):
Try something like this (pseudo code, I might have misremembered some method names):
public void Update(Customer entity)
{
using (MyContext ctx = new MyContext())
{
// Create a stub entity and attach it
Customer db = new Customer {ID = entity.ID};
ctx.Customers.Attach(db); // ctx.AttachTo("Customers", db) in 3.5 sp1
// ApplyPropertyChanges in 3.5 Sp1
ctx.ApplyCurrentValues(entity);
ctx.SaveChanges();
}
...
}
这code使用的<一个href="http://blogs.msdn.com/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx"相对=nofollow>存根实体把戏。你可以,如果你有关系,需要告诉EF更多的原始的实体,检查出的博客文章上面更多的,因为你可以做到这一点使用存根了。
This code uses the Stub Entity trick. You may if you have relationships need to tell EF more about the original entity, check out the blog post above for more because you can do that using stubs too.
另外,如果你不关心的所有关于并发你可能只是做到这一点:
Alternatively if you don't care at all about concurrency you could just do this:
public void Update(Customer entity)
{
using (MyContext ctx = new MyContext())
{
// pull the entity from the database
Customer db = ctx.Customers.First(c => c.ID == entity.ID);
// ApplyPropertyChanges in 3.5 Sp1
ctx.ApplyCurrentValues(entity);
ctx.SaveChanges();
}
}
希望这有助于
Hope this helps
亚历克斯·詹姆斯
这篇关于用一个简单的方法的EntityFramework .NET 4更新实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!