设想如下:
class Foo {
[Key]
public int Id { get; set; }
public List<Bar> Bars { get; set; }
}
class Bar {
[Key]
public int Id { get; set; }
public string Name { get; set; }
}我必须执行这样一个简单的crud操作:
public void InsertOrUpdateFoo(Foo foo) {
var db = new MyContext();
//here some pseudocode
if (foo exists) {
d.Foos.Add(foo);
} else {
//here which is the best solution?
//a good tradeoff between performance and code semplicity
//case 1: delete first and add
db.Foos.Remove(oldFoo);
db.Add(foo);
db.SaveChanges();
//case 2: there is some functionality that allows you to update the entity like:
db.Modify(oldEntity, newEntity);
}
db.Dispose();
}在更新场景中,哪一个似乎是最好的选择?
发布于 2014-03-05 03:20:01
根据http://forums.asp.net/t/1889944.aspx中的思想,您可以检查实体的ID属性是否是默认值,例如int的值为0。如果是这样的话,它是新的,应该添加。如果没有,那么更新它。
一旦实体附加到上下文,它的EntityState就可以将其指示给上下文。您可以通过实体的DbEntityEntry,通过上下文的Entry<T>()方法获得对此的访问。
您还需要在创建上下文时使用using语句,该语句将管理上下文的作用域,并在块结束时自动对其调用Dispose。
最好将其划分为实际将更改保存为insert或update的部分(很可能是存储库方法,但为了简单起见将在这里单独使用)和操作实体的代码。
方法的定义(基于您的代码):
public void InsertOrUpdateFoo(DbContext db, Foo foo) {
if (foo.ID == 0) { // assuming Foo's unique identifier is named ID
db.Entry(entity).State = EntityState.Added;
} else {
db.Entry(entity).State = EntityState.Modified;
}
db.SaveChanges();
}用法:
// for when you're creating new entities
var newFoo = new Foo();
newFoo.Name = "A Name";
using(var context = new MyContext())
{
context.Add(newFoo);
InsertOrUpdate(context. newFoo);
}
// ...
// for when you're using existing entities
// you have an ID from somewhere in variable "id"
using (var context = new MyContext())
{
var existingFoo = context.Find(id);
if (existingFoo != null)
{
existingFoo.Name = "ChangedTheName";
InsertOrUpdate(context, existingFoo);
}
}https://stackoverflow.com/questions/21674488
复制相似问题