Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'No suitable constructor found for entity type' when doing EF Core migration (SmartEnum)

I am attempting to run update-database to migrate some changes that I made to my db.

It all goes well until I get the following error:

No suitable constructor found for entity type 'ReportType'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'id', 'name' in 'ReportType(string id, string name)'.

Here is the code for ReportType.cs:

public class ReportType : SmartEnum<ReportType, string>
    {
        public static readonly ReportType ReportType1 = new ReportType("Blah", "Blah");
        public static readonly ReportType ReportType2 = new ReportType("Blah", "Blah");
        public static readonly ReportType ReportType3 = new ReportType("Blah", "Blah");

        // required for EF, but breaking for SmartEnum
        // private ReportType() {}

        private ReportType(string id, string name) : base(name, id)
        {

        }
    }

As you can see in the commented section of that code, having a parameterless constructor would normally fix this issue for EF Core, but SmartEnum doesn't have a parameterless constructor base.

There was a commit to the SmartEnum library on Arpil 27th, 2018 that added a parameterless constructor so that this issue wouldn't exist, but that change was removed in a later commit and I am unsure how to proceed without it.

That commit can be found here: https://github.com/ardalis/SmartEnum/commit/870012d406609a4a8889fdde2139750dc618d6a9

And was removed in this commit: https://github.com/ardalis/SmartEnum/commit/1c9bf3ede229fcb561330719cd13af67dcf92ad7

Any help is greatly appreciated!

EDIT:

Here's my solution to this issue as per Ivan's comments:

            modelBuilder.Entity<Report>()
                .Property(p => p.ReportType)
                .HasConversion(
                    p => p.Value,
                    p =>ReportType.FromValue(p));
like image 507
evantw Avatar asked Dec 27 '19 16:12

evantw


1 Answers

In OnModelCreating of ApplicationDbContext.cs:

modelBuilder.Entity<Report>()
            .Property(p => p.ReportType)
            .HasConversion(
                p => p.Value,
                p =>ReportType.FromValue(p));
like image 161
evantw Avatar answered Oct 19 '22 00:10

evantw