1

我有具有 category1 和 category2 字段的 Product 表,

并且每个字段都包含一个数字(ID),表示类别表ID(FK)。

我想在检索数据时为设置的类别名称添加实体,但我不知道如何使 category1_name 和 category2_name 可以具有类别名称。(很难解释=3)

前任)

public class Product
{
  [Key]
  public int no {get; set;}
  public int category1 {get; set;}  // category table ID number
  public int category2 { get; set;} // category table ID number

  public virtual Category category1_name {get; set;}
  public virtual Category category2_name {get; set;}
}


public class Category
{
  [Key]
  public int no {get; set;}
  public string category {get; set;}
}

但是当我尝试检索数据时,我得到了一个错误,

“on 子句”中的未知列“Extent1.category1_name_no”

如何将 category1_name 映射到类别表 ID?

4

1 回答 1

3

您如何期望 EF 知道哪个标量属性映射到哪个导航属性。您必须使用 fluent API 或数据注释来配置正确的映射。

public class Product
{
  [Key]
  public int no {get; set;}
  public int category1 {get; set;}  // category table ID number
  public int category2 { get; set;} // category table ID number

  [ForeignKey("category1")]
  public virtual Category category1_name {get; set;}

  [ForeignKey("category2")]
  public virtual Category category2_name {get; set;}
}

您应该考虑遵循正确的命名约定来命名属性。

于 2012-11-06T04:36:54.693 回答