首页 > 解决方案 > 使用延迟加载通过实体框架获取实体父级

问题描述

我需要一种解决方案来使用 EF 延迟加载从孩子那里检索父对象。我有 10 个不相关的类可以使用一种类型的子类,因此不知道如何为其设置 LINQ 查询。我看过这里,但这让我觉得我必须知道孩子实际上与 Parent1 相关联。在链接中,我知道博客有帖子,但帖子不会有博客。我没有这种稳固的关系。

这是我的班级设置的示例:

public class Parent1 
{
    public int Parent1Id { get; set; }
    ... other properties ...
    public virtual Child Child { get; set; }
}

public class Parent2 
{
    public int Parent2Id { get; set; }
    ... other properties ...
    public virtual Child Child { get; set; }
}

public class Parent3
{
    public int Parent3Id { get; set; }
    ... other properties ...
    public virtual Child Child { get; set; }
}

public class Child 
{
    public int ChildId { get; set; }
    ... other properties ...
}

孩子已Parent2通过DbContext.

在此之后,我检索子对象并想确定它与哪个父类相关联。

编辑

我有一个像这样的通用调用

public T GetById<T>(int id) where T : Base, new()
    {
        T entity = _Context.Set<T>().Find(id);
        return entity;
    }

然后我像这样打电话

Child childObj = DB.GetByID<Child>(id);

标签: c#entity-framework-6lazy-loadingentity-relationship

解决方案


推荐阅读