【问题标题】:ef-code-first one-to-many relation with tinyint primary key migration failsef-code-first 与 tinyint 主键迁移的一对多关系失败
【发布时间】:2019-01-08 13:23:35
【问题描述】:

我正在使用实体框架代码优先,我对此并不陌生。这是我的模型:

public class Tbl_Organization_Type
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public byte fld_organization_type_id { get; set; }

    [MaxLength(100)]
    public string fld_organization_type_name { get; set; }

    public byte? fld_sort { get; set; }

    public ICollection<Tbl_Organization> Tbl_Organization { get; set; }

}



public class Tbl_Organization
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long fld_organization_id { get; set; }
    public long? fld_organization_parent_id_ref { get; set; }

    [StringLength(500)]
    public string fld_organization_name { get; set; }

    [StringLength(200)]
    public string fld_organization_address { get; set; }

    [ForeignKey("fld_location_id_ref")]
    public Tbl_Personnel_Location Tbl_Personnel_Location { get; set; }

    [ForeignKey("fld_organization_type_id_ref")]
    public Tbl_Organization_Type Tbl_Organization_Type { get; set; }
}

当我添加 ( add-migration personnel_1 -context PersonnelDbContext ) 它给了我以下错误:

从 'Tbl_Organization.fld_organization_type_id' 到 具有外键属性的“Tbl_Organization_Type.Tbl_Organization” {'fld_organization_type_id_ref' : Nullable} 无法定位 主键 {'fld_organization_type_id' : byte} 因为它不是 兼容。

配置一个主键或一组兼容的外键 这种关系的关键属性。

【问题讨论】:

    标签: c# ef-code-first one-to-many entity-framework-migrations


    【解决方案1】:

    这看起来不像是正确的模型(fld_organization_type_id_ref 未显示或输入错误)。 IAC,该字段需要与 Tbl_Organization_Type(字节)的主键具有相同的类型。试试:

    public class Tbl_Organization
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long fld_organization_id { get; set; }
        public byte? fld_organization_type_id_ref { get; set; }  // This FK needs to match referenced PK type 
        // Are you missing or not showing fld_location_id_ref
    
        [StringLength(500)]
        public string fld_organization_name { get; set; }
    
        [StringLength(200)]
        public string fld_organization_address { get; set; }
    
        [ForeignKey("fld_location_id_ref")]
        public Tbl_Personnel_Location Tbl_Personnel_Location { get; set; }
    
        [ForeignKey("fld_organization_type_id_ref")]
        public Tbl_Organization_Type Tbl_Organization_Type { get; set; }
    }
    

    同样,您需要显示/定义字段 fld_location_id_ref 并将类型与引用表 Tbl_Personnel_Location 匹配。

    【讨论】:

      猜你喜欢
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多