包含没有链接到 DbSet

问题描述

使用 universal PredicateBuilder 可以在不链接到 DbSet 的情况下构建谓词。例如我有

public class Сountry
{
    public int Id { get; set; }
    public bool IsSchengen { get; set; }
}

public class Institute
{ 
    public int Id { get; set; }
    public int CountryId { get; set; }
    public bool IsNational { get; set; }
    public string Title { get; set; }
}

使用 PredicateBuilder 构建谓词:

public static Expression<Func<Institute,bool>> BuilPredicate(bool isNational)
{
    var predicate = new PredicateBuilder<Institute>()
           .And(ao => ao.IsNational == isNational);
    
    return predicate.Build();
}

现在我需要按国家过滤研究所:

public static Expression<Func<Institute,bool>> BuilPredicate(
    bool isNational,bool countryIsSchengen,DbContext db) // <== don't want to pass link to DbContext 
{
    var predicate = new PredicateBuilder<Institute>()
           .And(ii => ii.IsNational == isNational);
    

    // filter by countries
    // question: how to make the same without DbContext

    var countyIds = db.Set<Сountry>()
        .Where(cc => cc.IsSchengen == countryIsSchengen)
        .Select(cc => cc.Id);
    
    predicate.And(ii => countyIds.Contains(ii.CountryId));
        

    return predicate.Build();
}

是否可以在不链接到 DbContext 的情况下创建这样的谓词? 并且没有导航国家属性

public class Institute
{ 
    public int Id { get; set; }

    // without this 
    // public Country Country { get; set; }

    public int CountryId { get; set; }
    public bool IsNational { get; set; }
    public string Title { get; set; }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)