aqu*_*les 5 c# entity-framework ef-code-first
我正在使用.NET Framework 4.0和Entity Framework v6代码优先.
我正在创建使用复合主键的3个表(" Indicadores "," Campos "和" Codigos "),但是在生成模型时收到错误:
在模型生成期间检测到一个或多个验证错误:
Codigos_Campos_Target_Codigos_Campos_Source ::关系约束中的从属角色和主要角色中的属性数必须相同.
代码在这里:
public class Indicadores
{
[Key, Column(Order = 0)]
public Int32 Nro_Serie { get; set; }
[MaxLength(31)]
public string Nombre { get; set; }
public List<Campos> campo { get; set; }
}
public class Codigos
{
[Key, Column(Order = 0), DataType("nvarchar"), MaxLength(31)]
public string Codigo {get;set;}
[MaxLength(31)]
public string Descripcion1 {get;set;}
[MaxLength(31)]
public string Descripcion2 {get;set;}
public Int32 CantidadPesadas {get;set;}
public Int32 PesoTotal {get;set;}
[Key, Column(Order = 1)]
public Int16 Nro_Campo { get; set; }
[ForeignKey("Nro_Campo")]
public Campos Campos { get; set; }
}
public class Campos
{
[Key, Column(Order = 0), DataType("smallint"), DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
public Int16 Nro_Campo {get;set;}
[Required]
public string Nombre {get;set;}
public List<Codigos> codigo { get; set; }
[Key, Column(Order = 1)]
public Int32 Nro_Serie { get; set; }
[ForeignKey("Nro_Serie")]
public Indicadores Indicadores { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
以前,我使用" Campos "和" Codigos "表没有错误; 当我包含" Indicadores "表时会出现问题.
知道怎么解决这个问题?
你正在配置错误的Campos和之间的一对多关系Codigos.从属的FK必须包含主PK的所有列.此外,您不需要在PK Indicadores实体中指定列顺序,您只有一个PK.你的模型是这样的:
public class Indicadores
{
[Key]
public Int32 Nro_Serie { get; set; }
[MaxLength(31)]
public string Nombre { get; set; }
public List<Campos> campo { get; set; }
}
public class Codigos
{
[Key]
[Column(Order = 0)]
[DataType("nvarchar")]
[MaxLength(31)]
public string Codigo { get; set; }
[MaxLength(31)]
public string Descripcion1 { get; set; }
[MaxLength(31)]
public string Descripcion2 { get; set; }
public int CantidadPesadas { get; set; }
public int PesoTotal { get; set; }
[Key,ForeignKey("Campos"),Column(Order = 1)]
public Int16 Nro_Campo { get; set; }
[ForeignKey("Campos"), Column(Order = 2)]
public Int32 Nro_Serie { get; set; }
public Campos Campos { get; set; }
}
public class Campos
{
[Key, Column(Order = 1)]
[DataType("smallint")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
public Int16 Nro_Campo { get; set; }
[Required]
public string Nombre { get; set; }
public List<Codigos> codigo { get; set; }
[Key, Column(Order = 2)]
public Int32 Nro_Serie { get; set; }
[ForeignKey("Nro_Serie")]
public Indicadores Indicadores { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我将Nro_SerieFK属性添加到,Codigos并且我更改Campos实体的PK中的顺序,以使它们与FK 的顺序相匹配Codigos.