我在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_tool表
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"
};
}发布于 2012-06-21 12:00:42
您应该能够编写类似这样的代码(假设在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()
)
};换句话说..
发布于 2012-06-21 12:04:17
您没有设置任何外键,这意味着您无法获得映射实体的自动“导航属性”。您必须更新数据库,然后重新生成映射,或者使用工具箱自己添加映射。
编辑:
好的,让我们列出一个非常简短的清单。
Properties窗格来进行检查。展开Child和Parent属性并验证它们是否为空。如果到目前为止一切都做对了,那么单击Unit_Tool和Unit之间的关联应该会显示一个名为Units的Child属性。
如果缺少关联,可以通过以下方式添加一个:
Toolbox.Association工具,该对象定义了保存外键的对象上的主。这将弹出一个对话框,它应该是非常不言自明的。
HTH。
编辑:
通过修改你现有的代码解决了这个问题(感谢你的上传)。问题非常简单,但并不是很明显:在每个表中都需要有一个标识符列,否则Linq- to -不会在数据上下文中创建子集合引用。因此,由于您只将unit_tool用作一个数据透视表(完全可以接受),并且在每一行上没有唯一的ID,因此不会得到“导航属性”。要解决这个问题,只需向unit_tool表添加一个主键字段(您不必实际使用它-它只是用于对象关系管理),重新创建实体映射,然后,您的查询将按原样工作。
我不得不说,这一点乍一看并不明显。我从来没有遇到过这个问题,因为我总是出于习惯创建一个唯一的标识符……
https://stackoverflow.com/questions/11131278
复制相似问题