How to return Inserted Updated Id in a Merge query

63 Views Asked by At

I have 2 tables in my database:

Table dbo.Customers:

Id Name
1 Customer1
2 Customer2

Table dbo.Images

Id OwnerId ImageUrl OwnerType
1 1 abc.jpg Info
2 10 xyx.jpg Products
3 1 customer1.jpg Customer
4 2 customer2.jpg Customer

Here Pk 3 and 4 have the OwnerTypeId that matches the Customer table.

OwnerId basically has a FK relationship with the Customer table and Ownertype is the name of the table.

What I want to do is

  • Update Images table if the record exist
  • Otherwise create a new record

What I have done so far:

I use a Merge query to update the record if exist otherwise create the new record in the Image table

public Task<int> GetInsertedUpdatedId(int customerId, string ImageUrl, Cancellationtoken cancellationToken)
{
    await db.Images
            .Merge()
            .Using(new[] { new { OwnerId = customerId} })
                 .On((_new, old) => _new.OwnerId == old.OwnerId)
                 .UpdateWhenMatched((old, _new) => new Image
                     {
                          ImageUrl = Image.ImageUrl,                                                
                          UpdatedAt = Sql.CurrentTimestampUtc
                     })
                 .InsertWhenNotMatched(_new => new Image
                     {
                          OwnerId = _new.OwnerId,
                          OwnerType = ImageOwnerType.Customer,                                                
                          CreatedAt = Sql.CurrentTimestampUtc,
                          UpdatedAt = Sql.CurrentTimestampUtc,
                     })              
            .MergeAsync(cancellationToken);
 
    int insertedOrUpdatedId = await db.Images
                 .Where(x => x.OwnerId == customerId)
                 .Select(x => x.Id)
                 .FirstOrDefaultAsync(cancellationToken);
}

What I want:

  • I want to find a way to return inserted/updated Id without making another database call to get insertedUpdatedId after the merge is completed.

Is there a way to do it in the merge query and return Inserted/Updated Id ?

Thank you for having a look .

0

There are 0 best solutions below