Skip to main content
 首页 » 编程设计

c#之Linq to Sql : how to get data之one to many

2024年02月20日12zhenyulu

我在 ASP.NET C# 中的应用程序。我用的是Linq to Sql,看图

//5个数据表:

// Unit table 
 
     id |   name    | unit_type_id          Unit_type    
       -------------------------                     
        1 | Unit 1  |     1                     id   |  name 
        2 | Unit 2  |     1                     -------------    
        3 | Unit 3  |     1                     1    |  Type 1 
        4 | Unit 4  |     2                     2    |  Type 2 
        5 | Unit 5  |     1                     3    |  Type 3 
        6 | Unit 6  |     3      
 
 
 
 
 //Tool table                                // tool_type   table 
 
    id  |   name    | tool_type_id              id   |  name 
    ----------------------------            -------------------  
    1   |   Tool 1  |     1                     1    |  Tool_type 1 
    2   |   Tool 2  |     2                     2    |  Tool_type 2 
    3   |   Tool 3  |     1                     3    |  Tool_type 3 
    4   |   Tool 4  |     2          
    5   |   Tool 5  |     3  

//单位工具表

unit_id | tool_id 
    --------------- 
    1   |    1 
    2   |    1 
    1   |    2 
    1   |    3 
    2   |    2 
    2   |    3 
    3   |    3 
    3   |    2 

我想在C#中使用linq to sql来获取类似的数据

//我要获取的表数据

Unit name  |  Unit type name  | Tool name 
------------------------------------------------- 
Unit 1     | Type 1           | tool 1, tool 2, tool 3 
Unit 2     | Type 1           | tool 1, tool 2, tool 3 
Unit 3     | Type 1           | tool 2, tool 3 
Unit 4     | Type 2           |  
Unit 5     | Type 1           |  
Unit 6     | Type 3           |  

我的代码很低

//创建新类

public class unit_list 
    { 
        //Unit name 
        public string unit_name { get; set; } 
        // Unit type name 
        public string unit_type_name { get; set; } 
        // Tool name 
        public string tool_name { get; set; } 
    } 

//函数获取数据

protected void show_unit() 
{ 
    // Create datacontext 
    for_testDataContext db = new for_testDataContext(); 
    //Query data 
    IQueryable<unit_list> CourseList = from cl in db.units 
                                        select new unit_list() 
                                        { 
                                            unit_name = cl.name, 
                                            unit_type_name = cl.unit_type.name, 
                                            tool_name = // how to get data like "tool1, tool 2, tool 3" 
                                        }; 
 
} 

请您参考如下方法:

你应该可以这样写(假设所有关系都在 Linq 中正确设置):

select new unit_list() 
{ 
    unit_name = cl.name, 
    unit_type_name = cl.unit_type.name, 
    tool_name = string.Join(", ",  
        cl.unit_tools.Select(ut => ut.tool.name).ToArray() 
    ) 
}; 

换句话说..

  1. 获取与 unit_tools 的一对多关系
  2. 在工具中选择相应的行并选择name列
  3. 加入得到单个逗号分隔的字符串