Why can't I return as a new custom class (cms.bo.Site) which implements ISite?
public IQueryable<ISite> GetSites()
{
return (from site in Db.Sites select new cms.bo.Site(site.id, site.name));
}
Why can't I return as a new custom class (cms.bo.Site) which implements ISite?
public IQueryable<ISite> GetSites()
{
return (from site in Db.Sites select new cms.bo.Site(site.id, site.name));
}
Basically LINQ to SQL doesn't know what that constructor will do - it wants to try to convert that into a SQL query, but doesn't know how. Do you need to be able to add extra bits to the query afterwards? If not, you could do:
public IEnumerable<ISite> GetSites()
{
return Db.Sites.Select(x => new { x.id, x.name }) // Project in SQL
.AsEnumerable() // Do the rest in process
.Select(x => new cms.bo.Site(x.id, x.name))
.Cast<ISite>(); // Workaround for lack of covariance
}
EDIT: I had missed the variance aspect, and was assuming the query was failing at execution time. It's definitely worth trying just the call to Cast<ISite>()
as per tvanfosson's answer - but if that doesn't work, try the above :)
Try this:
return Db.Sites
.ToList()
.Select( s => new cms.bo.Site( s.id, s.name ) )
.Cast<ISite>()
.AsQueryable();