如何在 linq to sql 中连接字段
我想在 Linq to SQL 中实现以下 sql 查询。
SELECT TOP dbo.SiteDept.SiteDeptId, dbo.Site.SiteName + ' / ' + dbo.Dept.DeptName AS SiteDeptName, dbo.SiteDept.SiteId, dbo.SiteDept.DeptId,
dbo.Dept.DeptName
FROM dbo.SiteDept INNER JOIN
dbo.Site ON dbo.SiteDept.SiteId = dbo.Site.SiteId INNER JOIN
dbo.Dept ON dbo.SiteDept.DeptId = dbo.Dept.DeptId
我有一个 Linq to SQL 数据上下文,其中包含站点和部门实体以及将部门与站点关联的 SiteDept 实体。
我还在 SiteDept 部分类中添加了 SiteDeptName 的自定义字段。
我的想法如下。
public IEnumerable<SiteDept> GetAllSiteDepts()
{
var dataContext = new AtomWebDataContext(_connectionString);
var allSiteDepts = from sd in dataContext.SiteDepts
join s in dataContext.Sites
on sd.SiteId equals s.SiteId
join d in dataContext.Depts
on sd.DeptId equals d.DeptId
select new SiteDept()
{
SiteDeptId = sd.SiteDeptId,
SiteId = sd.SiteId,
DeptId = sd.DeptId,
SiteDeptName = s.SiteName + "/" + d.DeptName
};
return allSiteDepts;
}
但是我得到“不允许在查询中显式构造实体类型‘GPSO.Repository.SiteDept’。”
实现我想要的最好方法是什么?
I would like to achieve the following sql query in Linq to SQL.
SELECT TOP dbo.SiteDept.SiteDeptId, dbo.Site.SiteName + ' / ' + dbo.Dept.DeptName AS SiteDeptName, dbo.SiteDept.SiteId, dbo.SiteDept.DeptId,
dbo.Dept.DeptName
FROM dbo.SiteDept INNER JOIN
dbo.Site ON dbo.SiteDept.SiteId = dbo.Site.SiteId INNER JOIN
dbo.Dept ON dbo.SiteDept.DeptId = dbo.Dept.DeptId
I have a Linq to SQL data context with both a site and Dept entity and a SiteDept Entity that associates departments to the sites.
I have also added in a custom field in the SiteDept partial class for the SiteDeptName.
I was thinking something along the following lines.
public IEnumerable<SiteDept> GetAllSiteDepts()
{
var dataContext = new AtomWebDataContext(_connectionString);
var allSiteDepts = from sd in dataContext.SiteDepts
join s in dataContext.Sites
on sd.SiteId equals s.SiteId
join d in dataContext.Depts
on sd.DeptId equals d.DeptId
select new SiteDept()
{
SiteDeptId = sd.SiteDeptId,
SiteId = sd.SiteId,
DeptId = sd.DeptId,
SiteDeptName = s.SiteName + "/" + d.DeptName
};
return allSiteDepts;
}
However I get a "Explicit construction of entity type 'GPSO.Repository.SiteDept' in query is not allowed."
Whats the best way to achieve what I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是 SiteDept 是您的实体之一,它不允许您直接创建实体。处理此问题的方法是设置实体之间的关系并让 LINQ to SQL 获取所有实体,然后使用分部类上的属性来填写所需的名称。
The problem is that SiteDept is one of your entities and it won't let you create one directly. The way to handle this is by setting up the relationships between the entities and having LINQ to SQL fetch them all, then use the property on the partial class to fill in the name you need.