为什么我不能作为实现ISite的新的自定义类(cms.bo.Site)返回?
public IQueryable<ISite> GetSites()
{
return (from site in Db.Sites select new cms.bo.Site(site.id, site.name));
}发布于 2009-11-13 19:56:56
基本上,LINQ to SQL不知道构造函数会做什么-它想尝试将其转换为SQL查询,但不知道如何转换。之后,您是否需要能够向查询中添加额外的位?如果不是,您可以这样做:
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
}编辑:我错过了方差方面,并假设查询在执行时失败。根据tvanfosson的回答,只调用Cast<ISite>()绝对值得一试-但如果这不起作用,请尝试上面的方法:)
发布于 2009-11-13 19:58:02
试试这个:
return Db.Sites
.ToList()
.Select( s => new cms.bo.Site( s.id, s.name ) )
.Cast<ISite>()
.AsQueryable();https://stackoverflow.com/questions/1728768
复制相似问题