简体   繁体   English

实体框架 - 根据外键添加对象

[英]Entity Framework - Add objects depending on ForeignKey

I'm working on a semi-enterprise WPF Application, using EF6+ (any version is okay, I can update it any time I like).我正在开发一个半企业 WPF 应用程序,使用 EF6+(任何版本都可以,我可以随时更新它)。

I already have the database set-up (from previous project, it's a MSSQL db), and I'm doing code first obviously.我已经设置了数据库(从以前的项目开始,它是一个 MSSQL 数据库),而且我显然是先做代码的。 I'll use mock objects due to NDA.由于保密协议,我将使用模拟对象。

I would like to know what to do in order for EF to inject Son object from the database into the Man object as marked by Foreign Key.我想知道该怎么做才能使 EF 将Son对象从数据库注入到由外键标记的Man对象中。 eg:例如:

[Table("Man")]
public class Man : ObservableObject
{
    private int _id;

    private int _sonId;
    private Son _son;

    public int Id
    {
        get => _id;
        set => Set(() => Id, ref _id, value);
    }

    [ForeignKey("SonId")]
    public Son Son
    {
        get => _son;
        set => Set(() => Son, ref _son, value);
    }

    public int SonId
    {
        get => _sonId;
        set => Set(() => SonId, ref _sonId, value);
    }
}

[Table("Son")]
public class Son : ObservableObject
{
    private int _id;

    public int Id
    {
        get => _id;
        set => Set(() => Id, ref _id, value);
    }
}

I properly retrieve (using their respective repositories) objects from the database, however the Foreign Key object ( Son ) is not mapped (it's null).我从数据库中正确检索(使用它们各自的存储库)对象,但是外键对象( Son )没有映射(它是空的)。 Is this not an option in EF or I'm doing something wrong?这不是EF中的一个选项还是我做错了什么?

Repository存储库

public async Task<IEnumerable<Man>> GetAll()
{
    using (var ctx = new DatabaseContext())
    {
        return await ctx.Men.ToListAsync();
    }
}

I did not use any [Key] annotation, because I assume EF associates Id field as a primary key since my table PK is Id , and I have some validation in other classes like [StringLength] and [Range(1,10)] , etc... Which I assume is not relevant for this problem.我没有使用任何[Key]注释,因为我假设 EF 将 Id 字段作为主键,因为我的表 PK 是Id ,并且我在其他类中进行了一些验证,例如[StringLength][Range(1,10)] ,等等......我认为这与这个问题无关。

With EF6 you can use Include to eager load your child objects.使用 EF6,您可以使用Include预先加载您的子对象。 I am not aware of a way to load multiple children without chaining Includes.我不知道在不链接 Includes 的情况下加载多个子项的方法。 You could create an extension method for loading all the children as shown here .你可以创建如图所示加载所有儿童的扩展方法在这里 Also note there are some changes with EF Core .另请注意EF Core有一些更改。

BTW, your class could be simplified if you are not altering the backing fields:顺便说一句,如果您不更改支持字段,则可以简化您的课程:

public class Man : ObservableObject  // ToTable Man by default
{
    public int Id { get; set; } //PK by convention

    public int SonId { get; set; } // FK by convention
    public Son Son { get; set; } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM