c# – EF条件包含实体类型

前端之家收集整理的这篇文章主要介绍了c# – EF条件包含实体类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请假设这个架构:
public class Mammal
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Dog : Mammal
{
    public int TailId { get; set; }
    public Tail Tail { get; set; }
}

public class Bat : Mammal
{
    public int WingId { get; set; }
    public Wing Wing { get; set; }
}

public class Buffalo : Mammal
{
    public virtual ICollection<Horn> Horns { get; set; }
}

public class Tail
{
    public int Id { get; set; }
    ...
}

public class Wing
{
    public int Id { get; set; }
    ...
}

public class Horn
{
    public int Id { get; set; }
    ...
}

现在,我的背景:

public class MyContext : DbContext
{
    public DbSet<Mammal> Mammals { get; set; }
}

所以,我想只做一个SQL查询,并包含(并加载)所有嵌套实体,如:

var query = myContext.Mammals
    .IncludeIfTypeIs<Dog>(d => d.Tail)
    .IncludeIfTypeIs<Bat>(b => b.Wing)
    .IncludeIfTypeIs<Buffalo>(b => b.Horns)
    ...
    ...
;

我知道我可以单独做,但我不想要因为我有很多实体,我需要最小化数据库请求.

我不想使用延迟加载,因为这也会产生许多数据库请求.

怎么实现呢?

解决方法

你能尝试这样的事吗:
public static class Extensions
{
    public static IQueryable<Mammal> IncludeExtraEntities<Mammal,T>(this IQueryable<Mammal> query,T derivedType) where T :Mammal
    {
        if (derivedType is Dog)
            return query.Include("Tail");
        if (derivedType is Bat)
            return query.Include("Wing");
        return query;
    }
}

然后在你的db调用中:

var query = myContext.Mammals.IncludeExtraEntities(typeof(Dog));

也许这会奏效.

猜你在找的C#相关文章