【问题标题】:I am getting this error: "The entity type 'DisplayFormatAttribute' requires a primary key to be defined."我收到此错误:“实体类型 'DisplayFormatAttribute' 需要定义主键。”
【发布时间】:2019-10-26 11:01:52
【问题描述】:

我收到了这个错误

“实体类型'DisplayFormatAttribute'需要定义一个主键。”当我尝试运行此代码时在终端上

Dotnet ef migrations add firstMigrationAddModels

我正在使用 Entity-framework core 2.0 创建代码优先数据库迁移

我有许多模型(类),一个类继承自另一个,为了解决这个问题,我使用了实体框架核心的继承功能,称为按层次结构表 (TPH)

https://www.learnentityframeworkcore.com/inheritance

我把派生类和基类都放在了 dbcontext 的 Dbset 中

public DbSet<Person> people { get; set; }
public DbSet<Student> students { get; set; }

STUDENT 类没有 PK,因为 Person 有它。

我也有具有多对多关系的类,我通过创建桥接类解决了这个问题

错误说我需要“DisplayFormatAttribute”中的主键 但我无权访问该课程

我在我的模型中使用 Maxlength() 和 minlength() 等 DataAnotationAttributes,所以我正在以某种方式访问​​该类。

我使用的其他类型是 PhoneAttribute,EmailAddressAttribute

[MaxLength(15)]
public PhoneAttribute Phone { get; set; }
[MaxLength(254)]
public EmailAddressAttribute Email { get; set; }

【问题讨论】:

    标签: c# entity-framework ef-code-first entity-framework-core


    【解决方案1】:

    我解决了。问题是我的电话号码和电子邮件类型属性

    public PhoneAttribute Phone { get; set; }
    public EmailAddressAttribute Email { get; set; }
    

    PhoneAttribute 和 EmailAddressAttributes 没有 SQL 服务器等效类型

    我把它们拿出来,分别改成int和string,就成功了

    public int Phone { get; set; }
    public string Email { get; set; }
    

    【讨论】:

      【解决方案2】:

      您必须使用数据注释[Key] 设置您的属性之一

      [Key] 实际上是您的数据表的标识符。

      【讨论】:

      • 我加了,不行。我在所有类中都有 Id 字段,因此 ef core 非常聪明,可以将其用作 PK
      【解决方案3】:

      我解决了。问题是我的电话号码和电子邮件类型属性

      public PhoneAttribute Phone { get;放; } 公共 EmailAddressAttribute 电子邮件 { 获取;放; } PhoneAttribute 和 EmailAddressAttributes 没有 SQL 服务器等效类型

      我把它们拿出来,分别改成int和string,就可以了

      公共 int 电话 { 获取;放; } 公共字符串电子邮件{获取;放; }

      Т他为我工作,非常感谢你

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-16
        • 2022-11-30
        • 2021-07-23
        • 2021-11-27
        • 2018-08-13
        • 2019-09-13
        • 1970-01-01
        相关资源
        最近更新 更多