如何使用使用实体框架做一个MERGE时,我不知道,如果记录存在? [英] How can I use use Entity Framework to do a MERGE when I don't know if the record exists?
问题描述
在这太回答有关实体框架和合并的例子如何code是这样的:
In this SO answer about Entity Framework and MERGE, the example for how to code it is this:
public void SaveOrUpdate(MyEntity entity)
{
if (entity.Id == 0)
{
context.MyEntities.AddObject(entity);
}
else
{
context.MyEntities.Attach(entity);
context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
}
这假定您已经知道,如果要UPSERT实体存在与否;在这种情况下,检查 entity.Id
。但是,如果你不知道,如果该项目存在与否?举例来说,在我的情况,我导入从供应商记录到我的数据库,以及给定的记录可能会或可能不会已经导入。我想,如果它的存在是为了更新记录,否则添加。但是供应商的标识已被设置在这两种情况下
This assumes that you already know if the entity that you want to upsert exists or not; in this case you check entity.Id
. But what if you don't know if the item exists or not? For instance, in my case, I'm importing records from a vendor into my database, and a given record may or may not have already been imported. I want to update the record if it exists, otherwise add it. But the vendor's id is already set in both cases.
我看不出有什么办法做到这一点,除非我简单地问了数据库,如果记录是已经存在,这违背了合并后的整个目的。
I can't see any way to do this unless I simply ask the database if the record is there already, which defeats the whole purpose of MERGE.
推荐答案
我用的 AddOrUpdate 在这种情况下。不过,我相信它首先查询数据库,以便决定发出插入或更新。
I use AddOrUpdate in this situation. However, I believe it does query the database first in order to decide to issue an insert or update.
context.MyEntities.AddOrUpdate(e => e.Id, entity);
更新:
我跑过我的调试日志文件。首先,它运行:
I ran through my debug log files. First it runs:
SELECT TOP (2) ... WHERE 1 = [Extent1].[Id]
然后运行或者:
Then it runs either:
INSERT [dbo].[TestTable](...) VALUES (...)
SELECT [Id]
FROM [dbo].[SystemSettings]
WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()
或
UPDATE [dbo].[TestTable]
SET ...
WHERE ([Id] = @2)
更新2: 这里有一个有趣的扩展方法的使用合并: <一href="https://gist.github.com/ondravondra/4001192">https://gist.github.com/ondravondra/4001192
Update 2: Here's an interesting extension method the uses MERGE: https://gist.github.com/ondravondra/4001192
这篇关于如何使用使用实体框架做一个MERGE时,我不知道,如果记录存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!