与tinyint主键迁移的ef-code-first一对多关系失败

时间:2019-01-08 13:23:35

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

我使用的是Entity Framework Code-First,这是我的新手。这是我的模特:

String

当我添加Ellipse 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时) 它给了我下面的错误:

  

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

     

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

1 个答案:

答案 0 :(得分: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匹配。