Does EF upsert have to be done manually?

前端 未结 4 741
忘了有多久
忘了有多久 2021-02-01 04:39

I want to upsert reference members of an existing entity.

Do I have to write specific code for the upsert?

meaning: I have to check if I\'m handling an existing

4条回答
  •  忘掉有多难
    2021-02-01 04:54

    To avoid the overhead of a query and then insert, or throwing exceptions, you can take advantage of the underlying database support for merges or upserts.

    This nuget package does the job pretty well: https://www.nuget.org/packages/FlexLabs.EntityFrameworkCore.Upsert/

    Github: https://github.com/artiomchi/FlexLabs.Upsert

    Example:

    DataContext.DailyVisits
        .Upsert(new DailyVisit
        {
            // new entity path
            UserID = userID,
            Date = DateTime.UtcNow.Date,
            Visits = 1,
        })
        // duplicate checking fields
        .On(v => new { v.UserID, v.Date })
        .WhenMatched((old, @new) => new DailyVisit
        {
            // merge / upsert path
            Visits = old.Visits + 1,
        })
        .RunAsync();
    

    The underlying generated sql does a proper upsert. This command runs right away and does not use change tracking, so that is one limitation.

提交回复
热议问题