How to thow `DbUpdateConcurrencyException` manually in .net core?

.net-core asp.net-core c# entity-framework-core

Question

I want to throw Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException in my code, but DbUpdateConcurrencyException has single constructor:

public DbUpdateConcurrencyException(
      [NotNullAttribute] string message, 
      [NotNullAttribute] IReadOnlyList<IUpdateEntry> entries)

I pass null in second parameter but as [NotNullAttribute] says, it can't be null. In my try-catch code i just catch the DbUpdateConcurrencyException and i don't mind its properties (Message or ...).

Is there any way to throw and instance from this class out of the box? I know i can make a custom Exception but i'd rather DbUpdateConcurrencyException.

1
0
12/15/2019 4:35:47 PM

Accepted Answer

It seems, you are running EF core 2.2 or below, because the overloads you are looking for have been introduced in ef core 3.0. Therefore one answer will be upgrade to EF core 3.0 or newer,

If this is not an option, you can define your custom exception in the interim (I understand you'd rather avoid it but that's probably the cleanest way around it):

public class MyDbUpdateConcurrencyException : DbUpdateException
{
    public MyDbUpdateConcurrencyException(string message) : base(message, (Exception)null)
    {
    }
}

UPD As it's been pointed out in comments you can target different versions of .net core runtime with your current EF. I just wanted to point out that upgrading to EF core 3.0 might be tricky due to a few breaking changes it introduced, therefore passing an empty list (as Erik Philips suggests) will likely be a more fitting solution in your case.

1
12/15/2019 9:10:34 PM

Popular Answer

Simply pass in a list with a null entry.

Working DotNetFiddle Example

// @nuget: Microsoft.EntityFrameworkCore -version 2.2
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Update;                 
public class Program
{
    public static void Main()
    {
        throw new DbUpdateConcurrencyException("message"
          , new List<IUpdateEntry> { null }  );
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow