我想从某个(Blobs)表中只选择几列。我有以下字段:Id,RowVersion,Size,Signature,Blob,我想只选择前四个。我这样做:( --->是一个错误的地方)
public List<BlobDetails> GetAllBlobsNames()
{
RichTekstModelDataContext dc = new RichTekstModelDataContext();
var allBlobs = from b in dc.Blobs
orderby b.RowVersion descending
select new {b.Id, b.Size, b.Signature, b.RowVersion};
---> allBlobs.ToList<BlobDetails>();
}
public class BlobDetails
{
public int Id { get; set; }
public string Signature { get; set; }
public int Size { get; set; }
public System.Data.Linq.Binary RowVersion { get; set; }
}
当我尝试返回BlobDetails时发生错误 - 因为VS.08不知道如何从匿名类型(allBlobs)转换为List。
我不想选择所有值,因为Blob字段可能很重,我不想一直发送它。
你知道如何正确地做到这一点吗?
答案 0 :(得分:10)
如果BlobDetails
不是 LINQ实体,那么您可以直接执行此操作:
var qry = from b in dc.Blobs
orderby b.RowVersion descending
select new BlobDetails {
Id = b.Id, Size = b.Size,
Signature = b.Signature, RowVersion = b.RowVersion};
return qry.ToList();
然而;如果BlobDetails
是LINQ实体,则需要使用subrefuge:
var qry = from b in dc.Blobs
orderby b.RowVersion descending
select new {b.Id, b.Size, b.Signature, b.RowVersion};
var typedQry = from b in qry.AsEnumerable()
select new BlobDetails {
Id = b.Id, Size = b.Size,
Signature = b.Signature, RowVersion = b.RowVersion};
return typedQry.ToList();
AsEnumerable
打破了LINQ组合,使其有效。
答案 1 :(得分:6)
使用“select new {”,您将创建一个无法隐式转换为BlobDetails的匿名类型。相反,在select:
中明确声明您正在新建的类型var allBlobs = from b in dc.Blobs
orderby b.RowVersion descending
select new BlobDetails {Id = b.Id, .... };
allBlobs.ToList();