如果存在则更新行,否则使用实体框架插入逻辑 [英] Update Row if it Exists Else Insert Logic with Entity Framework

查看:17
本文介绍了如果存在则更新行,否则使用实体框架插入逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用实体框架实现更新行(如果存在),否则插入新行逻辑的最有效方法是什么?或者有没有这方面的模式?

What is the most efficient way to implement update row if it exists, else insert new row logic using Entity Framework? Or are there any patterns for this?

推荐答案

如果您正在使用附加对象(从上下文的同一实例加载的对象),您可以简单地使用:

If you are working with attached object (object loaded from the same instance of the context) you can simply use:

if (context.ObjectStateManager.GetObjectStateEntry(myEntity).State == EntityState.Detached)
{
    context.MyEntities.AddObject(myEntity);
}

// Attached object tracks modifications automatically

context.SaveChanges();

如果您可以使用有关对象键的任何知识,则可以使用以下内容:

If you can use any knowledge about the object's key you can use something like this:

if (myEntity.Id != 0)
{
    context.MyEntities.Attach(myEntity);
    context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
    context.MyEntities.AddObject(myEntity);
}

context.SaveChanges();

如果您不能通过对象的 ID 来确定对象的存在,则必须执行查找查询:

If you can't decide existance of the object by its Id you must execute lookup query:

var id = myEntity.Id;
if (context.MyEntities.Any(e => e.Id == id))
{
    context.MyEntities.Attach(myEntity);
    context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
    context.MyEntities.AddObject(myEntity);
}

context.SaveChanges();

这篇关于如果存在则更新行,否则使用实体框架插入逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆