其他分享
首页 > 其他分享> > CodeGo.net>如何在实体框架6的数据注释中添加复合外键

CodeGo.net>如何在实体框架6的数据注释中添加复合外键

作者:互联网

我正在使用Entity Framework 6开发ASP.NET应用程序.我已经有数据库,并且正在使用Code First现有的数据库方法.

我是两个表,第二个表具有Foriegn键以及它自己的主键.我已经使用了列顺序,但仍然收到以下错误.我在网上搜索,尝试了不同的组合,但仍然出现错误.

'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code Sys_Nav_FunctionHierarchyEntity_Sys_Nav_FunctionEntity_Source: : Multiplicity is not valid in Role  'Sys_Nav_FunctionHierarchyEntity_Sys_Nav_FunctionEntity_Source' in relationship 'Sys_Nav_FunctionHierarchyEntity_Sys_Nav_FunctionEntity'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

A级

 [Table("Sys_Nav_Function")]
 public class Sys_Nav_FunctionEntity
 {
    public Sys_Nav_FunctionEntity()
    { }


    [Key]
    public int Function_ID { get; set; }

    [StringLength(250)]
    [Required(ErrorMessage = "Required Title")]
    [Display(Name = "Function Title")]
    public string FunctionName { get; set; }

    [Required(ErrorMessage = "Required Hierarchy Level")]
    [Display(Name = "Hierarchy Level")]
    public int Hierarchy_Level { get; set; }


    public Sys_Nav_FunctionHierarchyEntity Sys_Nav_FunctionHierarchyEntity { get; set; }

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

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

B级

 [Table("Sys_Nav_FunctionHierarchy")]
public class Sys_Nav_FunctionHierarchyEntity
{
    public Sys_Nav_FunctionHierarchyEntity()
    {

    }


    [Key, Column(Order =0)]
    public int Hierarchy_ID { get; set; }

    [ForeignKey("Sys_Nav_FunctionEntity"), Column(Order =1)]
    public int Function_ID { get; set; }

    public int Parent_Function_ID { get; set; }

    public Sys_Nav_FunctionEntity Sys_Nav_FunctionEntity { get; set; }
}

enter image description here

解决方法:

尝试这个

[Table("Sys_Nav_FunctionHierarchy")]
public class Sys_Nav_FunctionHierarchyEntity
{
    public Sys_Nav_FunctionHierarchyEntity()
    {

    }


    [Key, Column(Order =0)]
    public int Hierarchy_ID { get; set; }

    [ForeignKey("Function_ID"), Column(Order =1)]
    public int Function_ID { get; set; }

    public int Parent_Function_ID { get; set; }

    public Sys_Nav_FunctionEntity Sys_Nav_FunctionEntity { get; set; }
}

您在B类中拥有的foriegn键被链接到表而不是属性.

我相信上面的代码应该给您正确的结果

标签:composite-key,entity-framework-6,data-annotations,c
来源: https://codeday.me/bug/20191026/1940318.html