【问题标题】:Add an inner or outer join based on a parameter根据参数添加内连接或外连接
【发布时间】:2019-06-12 17:08:23
【问题描述】:

这可能是一个简单/愚蠢的问题,但他们是否可以根据您收到的数据将内部或外部联接添加到 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
    }

}

【问题讨论】:

  • 有点类似question
  • 有点,但我想知道如何用asp ef语法编写它

标签: c# sql join asp.net-core entity-framework-core


【解决方案1】:

通过执行以下操作修复它:

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

【讨论】:

    【解决方案2】:

    我认为您的主要问题只是打字。使用var 存储初始查询会将其键入为DbSet<SomeObject>。要构建查询,您需要IQueryable<SomeObject>。换句话说,将您的初始行更改为:

    IQueryable<SomeObject> query = from o in _dbContext.SomeObjects;
    

    我自己不使用 LINQ-to-SQL,所以这可能有点不对劲,但我认为您只需执行以下操作:

    query = query join type in _dbContext.Types on o.TypeId equals type.ID;
    

    我知道它适用于 LINQ-to-Entities,例如:

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

    【讨论】:

    • 这没有用,但我在我的解决方案中使用声明修复了它。谢谢帮助!
    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多