c# - 执行 EF Core 迁移(SmartEnum)时“找不到适合实体类型的构造函数”

标签 c# entity-framework asp.net-core entity-framework-core entity-framework-migrations

我正在尝试运行 update-database迁移我对数据库所做的一些更改。

一切顺利,直到出现以下错误:

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)'.



这是 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)
        {

        }
    }

正如您在该代码的注释部分所看到的,拥有无参数构造函数通常可以解决 EF Core 的这个问题,但 SmartEnum 没有无参数构造函数基础。

2018 年 2 月 27 日 Arpil 提交了对 SmartEnum 库的提交,该库添加了一个无参数构造函数,因此该问题不存在,但该更改在以后的提交中被删除,我不确定没有它如何继续。

该提交可以在这里找到:https://github.com/ardalis/SmartEnum/commit/870012d406609a4a8889fdde2139750dc618d6a9

并在此提交中被删除:
https://github.com/ardalis/SmartEnum/commit/1c9bf3ede229fcb561330719cd13af67dcf92ad7

任何帮助是极大的赞赏!

编辑:

根据 Ivan 的评论,这是我对此问题的解决方案:
            modelBuilder.Entity<Report>()
                .Property(p => p.ReportType)
                .HasConversion(
                    p => p.Value,
                    p =>ReportType.FromValue(p));

最佳答案

在 ApplicationDbContext.cs 的 OnModelCreating 中:

modelBuilder.Entity<Report>()
            .Property(p => p.ReportType)
            .HasConversion(
                p => p.Value,
                p =>ReportType.FromValue(p));

关于c# - 执行 EF Core 迁移(SmartEnum)时“找不到适合实体类型的构造函数”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59503774/

相关文章:

c# - 如何使用 ForNpgsqlUseXminAsConcurrencyToken 创建的 EF Core 并发 token

c# - 为什么 IsEnabled 是 ILogger 接口(interface)的一部分?

ASP.NET 5 + Angular 2 路由(模板页面不重新加载)

c# - 如何使服务器仅在 SignalR 中运行

c# - 保存 3D int 数组的最快方法? (XNA\C#)

c# - 哈希表的 IEnumerator?

c# - WebAPI - 基于实体修饰属性的通用搜索服务

c# - 以编程方式获取嵌套的静态类名称并访问方法

c# - 如何将空白文本框值作为 null 传递给绑定(bind)日期时间

asp.net - 如何在 EntityDataSource 中使用 CASE 语句进行排序?