且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我不知道记录是否存在时,如何使用实体框架进行合并?

更新时间:2023-01-04 22:22:52

如果你想要一个没有存储过程的原子数据库 UPSERT 命令,并且你不担心上下文被更新,可能值得一提的是你也可以 wrapExecuteSqlCommand 调用中嵌入的 MERGE 语句:

If you want an atomic database UPSERT command without a stored procedure and you're not worried about the context being updated, it might worth mentioning that you can also wrap an embedded MERGE statement in an ExecuteSqlCommand call:

public void SaveOrUpdate(MyEntity entity)
{
    var sql =  @"MERGE INTO MyEntity
                USING 
                (
                   SELECT   @id as Id
                            @myField AS MyField
                ) AS entity
                ON  MyEntity.Id = entity.Id
                WHEN MATCHED THEN
                    UPDATE 
                    SET     Id = @id
                            MyField = @myField
                WHEN NOT MATCHED THEN
                    INSERT (Id, MyField)
                    VALUES (@Id, @myField);"

    object[] parameters = {
        new SqlParameter("@id", entity.Id),
        new SqlParameter("@myField", entity.myField)
    };
    context.Database.ExecuteSqlCommand(sql, parameters);
}

这并不漂亮,因为它在 EF 对实体的抽象之外工作,但它允许您利用 MERGE 命令.

This isn't pretty because it works outside EF's abstraction over entities but it will allow you to leverage the MERGE command.