我有一个场景,我必须更新实体,如果它存在或添加一个新的,如果它不。实体框架:更新实体或添加,如果它不存在
我想为此执行一个单一的方法(如果它是单次访问服务器,那将会很棒)。
在EF中是否有类似的东西?
现在我的代码如下所示:
var entity = db.Entities.FirstOrDefault(e => e.Id == myId);
if (entity == null)
{
entity = db.Entities.CreateObject();
entity.Id = myId;
}
entity.Value = "my modified value";
db.SaveChanges();
但我想避免的第一个查询,像这样:
var entity = new Entity();
entity.Id = myId;
entity.Value = "my modified value";
db.AddOrAttach(entity);
db.SaveChanges();
有什么相似?还是必须执行第一个查询?
谢谢
我的问题来看看这样做一般的保存与EF:http://stackoverflow.com/questions/6018711/generic-way-to-check-if-entity-exists-in-entity-framework的结果这是(根据需要插入或更新)写一个通用的保存方法。它很快变得混乱。 – Yuck