C# 基于参数添加内部联接或外部联接

C# 基于参数添加内部联接或外部联接,c#,sql,join,asp.net-core,entity-framework-core,C#,Sql,Join,Asp.net Core,Entity Framework Core,这可能是一个简单/愚蠢的问题,但它们是根据您接收的数据向SQL查询(使用实体框架)添加内部或外部联接的一种方法吗 示例 public bool method(int? typeId, int? categoryId){ var query = from o in _dbContext.SomeObjects; //JOIN type if(typeId != null){ //Add inner join with table types to quer

这可能是一个简单/愚蠢的问题,但它们是根据您接收的数据向SQL查询(使用实体框架)添加内部或外部联接的一种方法吗

示例

public bool method(int? typeId, int? categoryId){
    var query = from o in _dbContext.SomeObjects;

    //JOIN type
    if(typeId != null){
        //Add inner join with table types to query
        //Something like:  
        //query += join type in _dbContext.Types on o.TypeId equals type.ID
    }else{
        //Add outer join with table types to query
        //query += join type in _dbContext.Types on o.TypeId equals type.ID into types
        //             from type in types.DefaultIfEmpty()
    } 

    //Do same for category
    ...

    //Filters
    if(typeId != null){
        query += where type.ID == typeId
    }

    if(categoryId != null){
        query += where category.ID == categoryId
    }

}

我认为你的主要问题是打字。使用
var
存储初始查询将其键入
DbSet
。要生成查询,您需要
IQueryable
。换句话说,将初始行更改为:

IQueryable<SomeObject> query = from o in _dbContext.SomeObjects;
我知道它可以与LINQ一起工作,例如:

query = query.Include(x => x.Types);

通过执行以下操作修复此问题:

var query = from o in _dbContext.SomeObjects
                join type in _dbContext.Types on o.TypeId equals type.ID
            where (typeId == null || type.ID == typeId) &&

有点类似,但我想知道如何使用asp ef语法编写它,虽然它不起作用,但我在解决方案中用语句修复了它。谢谢你的帮助!
var query = from o in _dbContext.SomeObjects
                join type in _dbContext.Types on o.TypeId equals type.ID
            where (typeId == null || type.ID == typeId) &&