使用 Entity Framework 数据注解实现与预加载的一对多关系

Using Entity Framework Data Annotations to Achieve One to Many Relationship With Eager Loading

我见过很多不使用数据注释的示例,并且可以使一对一关系正常工作,但很难处理一对多关系。

我们会随机抽取样品重量的零件,以确保我们的机房生产符合规格。 Material 的一对一关系将加载。一对多的 QualityMeasurements 有问题。

有人有这方面的经验吗?

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class Part {

    [Key]
    public string PartID { get; set; }
    public string PartNumber { get; set; }

    [ForeignKey("MaterialID")]
    public virtual Material Material { get; set; }
    public int MaterialID { get; set; }

    [ForeignKey("PartNumber")]
    public virtual ICollection<QualityMeasurement> Qualities { get; set; }
}

public class Material {

    [Key]
    public int MaterialID { get; set; }
    public string Title { get; set; }
    public double Density { get; set; }

}

public class QualityMeasurement  {

    public int QualityID { get; set; }
    [Key]
    public string PartNumber { get; set; }
    public double UnitWeight { get; set; }

}

您遇到问题是因为在 one-to-many 关系中,foreign key 应该定义在 many 端并且应该与 primary key 相关联15=]边。

你的模型应该是这样的:

public class Part {

    [Key]
    public string PartID { get; set; }
    public string PartNumber { get; set; }

    [ForeignKey("MaterialID")]
    public virtual Material Material { get; set; }
    public int MaterialID { get; set; }

    public virtual ICollection<QualityMeasurement> Qualities { get; set; }
}

public class QualityMeasurement  {

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

    [ForeignKey("PartID")]
    public virtual Part Part { get; set; }
    public string PartID { get; set; }

    public double UnitWeight { get; set; }
}