实体框架中的外键声明
本文关键字:声明 框架 实体 | 更新日期: 2023-09-27 17:54:42
我的ForeignKey有问题。
错误:类型为mvccrystal . models的属性'co_art'上的ForeignKeyAttribute。Almacen'是无效的。在从属类型mvccrystal . models . almacen上找不到导航属性Articulo。Name值应该是一个有效的导航属性名。
My Classes声明:
public class Articulo
{
[Required]
public string co_art { get; set; }
public string des_art { get; set; }
public string modelo { get; set; }
public string co_lin { get; set; }
public string co_subl { get; set; }
public string co_cat { get; set; }
public string co_col { get; set; }
[ForeignKey("co_art")]
public ICollection<Almacen> Almacenes { get; set; }
}
public class Almacen
{
[Key, Column(Order = 0)]
public string co_alma { get; set; }
public string des_alm { get; set; }
[Required, ForeignKey("Articulo"), Column(Order = 1)]
public string co_art { get; set; }
public double stock_act { get; set; }
}
帮忙吗?谢谢,我是新来的。
您得到的异常应该指向正确的方向,因为它明确地说明了问题。它说,"导航属性‘Articulo’找不到……"……Almacen"。Name值应该是一个有效的导航属性名。"
好的,所以外键(即Articulo
)的Name值需要是Almacen
的导航属性,所以让我们这样做。
public class Almacen
{
[Key, Column( Order = 0 )]
public string co_alma { get; set; }
public string des_alm { get; set; }
[Required, ForeignKey( "Articulo" ), Column( Order = 1 )]
public string co_art { get; set; }
public double stock_act { get; set; }
public Articulo Articulo { get; set; }
}
在这样做之后,我得到了另一个错误,说co_art需要在Articulo
上是一个键,所以我添加了它。
public class Articulo
{
[Required]
[Key]
public string co_art { get; set; }
public string des_art { get; set; }
public string modelo { get; set; }
public string co_lin { get; set; }
public string co_subl { get; set; }
public string co_cat { get; set; }
public string co_col { get; set; }
[ForeignKey( "co_art" )]
public ICollection<Almacen> Almacenes { get; set; }
}
在那一刻,一切似乎都很愉快。
你的注释看起来不正确
你似乎想用注解来关联一对多关系。
Articulo 1 <--> * Almacen
键和外键的类型应为int。
我建议学习更多关于注释的教程,就像下面这些
- http://msdn.microsoft.com/en-us/data/jj591583.aspx
- http://www.entityframeworktutorial.net/code-first/dataannotation-in-code-first.aspx
你也可以用fluent api代替注解
- http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx