实体框架实体引用另外两次

时间:2015-02-20 07:22:44

标签: entity-framework one-to-many

我有一个产品类用于餐馆申请的订单:

public class Product
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

    public virtual ICollection<ServingChoice> ServingChoices { get; set; }
}

产品可以选择服务,如“每日汤”为用户提供了在少数产品中进行选择的选择。 产品和选择都是Product类型:

public class ServingChoice
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int ChoiceId { get; set; }

    public Product Product { get; set; }
    [InverseProperty("ServingChoices")]
    public Product Choice { get; set; }
}

我做错了,因为产品从不加载它的选择。该表似乎是正确创建的。 有什么帮助吗?

EDITED: 它看起来有点像,但反过来了。如果我手动将一些记录广告到数据库中,如下所示:

ProductID | ChoiceID
1           10
2           10
3           10

适用于Id = 10的产品。

1 个答案:

答案 0 :(得分:1)

我认为你的问题是因为你没有按照你应该的方式映射FK。试试这个:

public class ServingChoice
{
  //...
  [ForeignKey("Product")]
  public int ProductId { get; set; }
  [ForeignKey("Choice")]
  public int ChoiceId { get; set; }

  public Product Product { get; set; }

  [InverseProperty("ServingChoices")]
  public Product Choice { get; set; }
 }

顺便说一下,您正在配置两个一对多关系,但在涉及Product导航属性(在ServingChoice类中)的关系中,您没有定义另一端。如果您想这样做,您应该在Product实体中声明另一个导航属性:

public class Product
{
  [Key]
  //[DatabaseGenerated(DatabaseGeneratedOption.Identity)] this is not necessary, it's the default behavior
  public int Id { get; set; }
  public string Name { get; set; }
  public decimal Price { get; set; }

  public virtual ICollection<ServingChoice> ProductChoices { get; set; }
  public virtual ICollection<ServingChoice> ServingChoices { get; set; }
}

然后,在ServiceChoice类中,您应该在InverseProperty导航属性上添加Product注释,以明确指定关系的另一端是什么:

public class ServingChoice
{
  [Key]
  // [DatabaseGenerated(DatabaseGeneratedOption.Identity)] the same I explain before
  public int Id { get; set; }
  [ForeignKey("Product")]
  public int ProductId { get; set; }
  [ForeignKey("Choice")]
  public int ChoiceId { get; set; }

  [InverseProperty("ProductChoices")]
  public Product Product { get; set; }

  [InverseProperty("ServingChoices")]
  public Product Choice { get; set; }
 }

此外,您可以按照相同的想法使用 Fluent Api

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Entity<ServingChoice>().HasRequired(m => m.Product).WithMany(m => m.ProductChoices).HasForeignKey(m=>m.ProductId);
     modelBuilder.Entity<ServingChoice>().HasRequired(m => m.Choice).WithMany(m => m.ServingChoices).HasForeignKey(m=>m.ChoiceId);
}