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?
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.