更新实体和相关实体
问题描述:
的情况是:更新实体和相关实体
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 OPS是这样的:
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();
}
在更新方案,这似乎是最好的选择?
- 删除和添加
- 手动管理更新(的foreach子实体)
- 一些其他技术?
答
根据http://forums.asp.net/t/1889944.aspx中的想法,您可以检查实体的ID属性是否为默认值,例如int为0。如果是这样,它是新的,应该添加。如果不是,则更新它。
一旦实体连接到上下文,就可以通过它的EntityState
向上下文指示。您可以通过该实体的DbEntityEntry
通过上下文的Entry<T>()
方法获得对此的访问权限。
创建上下文时,您还需要使用using
语句,该语句将管理上下文的范围,并在块结束时自动调用Dispose
。
最好将其拆分成实际上将更改保存为插入或更新的部分(存储库方法,很可能,但将在此处单独使用以简化)以及操作实体的代码。
定义的方法(根据您的代码):
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);
}
}