Linq to Sql查询多行子查询

时间:2014-12-18 10:52:14

标签: sql-server linq subquery

select * from Category where Cat_Id in (select Cat_Id from User_Core_Values where UserId = 1) ;

我一直试图在.Net的Linq中编写这个查询但是没有取得多大成功。子查询返回一个整数列表,从类别表中选择相应的类别列表。上面的SQL查询返回正确的结果,我似乎无法做到正确。帮助

我尝试了以下查询,但我得到'无法将int转换为bool错误。所以它显然不像我想的那样工作,但有人可以指出我正确的方向吗?

from c in Categories where c.Cat_Id == (from x in User_Core_Values where x.UserId = 1 select x.Cat_Id) select new { id = c.Cat_Id, cat = c.Content }

2 个答案:

答案 0 :(得分:0)

我不知道如何在linq中执行IN子句。但您可以按如下方式编写SQL语句:

select Category.* from User_Core_Values join Category on Category.Cat_Id = User_Core_Values.Cat_Id where UserId = 1;

这让我觉得你可以做以下事情:

IEnumerable<Category> categories = (from x in User_Core_Values where x.UserId = 1 select x.Categories).SelectMany(x => x);

SelectMany(x => x)应该将IEnumerable<IEnumerable<Category>>变为IEnumerable<Category>

答案 1 :(得分:0)

这可以通过基于公共User_Core_ValuesCat_Id上进行内部联接来实现:

var results = from c in Categories 
              join v in User_Core_Values on c.Cat_Id equals v.Cat_Id
              where v.UserId == 1
              select new { id = c.Cat_Id, cat = c.Content };

<强> Test C# Program

using System;
using System.Linq;

class Category
{
    public int Id { get; set; }
    public string Content { get; set; }
}

class UserCoreValue
{
    public int Id { get; set; }
    public int CategoryId { get; set; }
    public int UserId { get; set; }
}

class Test
{
    static void Main()
    {
    // Example customers.
    var categories = new Category[]
    {
        new Category{Id = 5, Content = "Design Studies"},
        new Category{Id = 6, Content = "Architecture"},
        new Category{Id = 7, Content = "Photography"},
        new Category{Id = 8, Content = "Graphic Arts"}
    };

    // Example orders.
    var user_core_values = new UserCoreValue[]
    {
        new UserCoreValue{Id = 1, CategoryId = 5, UserId = 1},
        new UserCoreValue{Id = 2, CategoryId = 6, UserId = 1},
        new UserCoreValue{Id = 3, CategoryId = 7, UserId = 7},
        new UserCoreValue{Id = 4, CategoryId = 8, UserId = 1},
        new UserCoreValue{Id = 1, CategoryId = 5, UserId = 2},
        new UserCoreValue{Id = 2, CategoryId = 6, UserId = 3},
        new UserCoreValue{Id = 3, CategoryId = 7, UserId = 2},
        new UserCoreValue{Id = 4, CategoryId = 8, UserId = 1}
    };

    // Join on the ID properties.
    var query = from c in categories 
                join v in user_core_values on c.Id equals v.CategoryId
                where v.UserId == 1
                select c;

    // Display joined groups.
    foreach (var category in query)
    {
        Console.WriteLine("{0} - {1}", category.Id, category.Content);
        // Displays
        //5 - Design Studies
        //6 - Architecture
        //8 - Graphic Arts
        //8 - Graphic Arts
    }
  }
}