我在ASP.NET C#中的应用。我使用Linq到Sql,看看图片
// 5 data talbe:
// 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_tool table
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"
};
}
答案 0 :(得分:2)
你应该可以写这样的东西(假设在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 :(得分:2)
您没有设置任何外键,这意味着您没有获得映射实体的自动“导航属性”。您必须更新数据库然后重新生成映射,或者使用工具箱自行添加它们。
修改强>
好的,让我们写一个非常简短的清单。
Properties
窗格。展开Child
和Parent
属性并验证它们不是
空。如果到目前为止您已完成所有操作,点击Unit_Tool
和Unit
之间的关联应该会显示一个名为Child
的{{1}}媒体资源。
如果您错过了关联,可以通过以下方式添加:
Units
。{/ li>中的Association
工具
这将显示一个非常明显的对话框。
HTH。
编辑:
通过使用现有代码来解决这个问题(感谢上传)。问题非常简单,但并不十分明显:您需要在每个表中都有一个标识符列,或者Linq-to-SQL不会在数据上下文中创建子集合引用。所以,因为你使用Toolbox
只是一个数据透视表(完全可以接受),而且每行没有唯一的ID,所以你没有获得“导航属性”。要解决这个问题,只需添加一个主键字段(您不必实际使用它 - 它仅用于ORM)到unit_tool
表,重新创建实体映射,以及中提琴!,您的查询将按原样运行。
我不得不说,乍一看这并不明显。我从未遇到过这个问题,因为我总是根据习惯创建一个独特的标识符......