Thursday, May 5, 2011

Linq to Sql - return selected specified columns

I would like to select only few columns from a certain (Blobs) table. I have fields like: Id, RowVersion, Size, Signature, Blob, and I want to select only first four. I do it like this: (---> is an error place)

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; }     
}

Error occures when I am trying to return BlobDetails - as VS.08 doesn't know how to convert from Anonymous Type (allBlobs) to List.

I do not want to select all values, because Blob field can be quite heavy and I don't want to send it all the time.

Do you have any idea how to do it properly?

I hope I am clear on my issue.

From stackoverflow
  • With "select new {" you are creating an anonymous type which cannot be implicitly cast to BlobDetails. Instead, explicitly declare the type you are newing within the select:

    var allBlobs = from b in dc.Blobs
               orderby b.RowVersion descending
               select new BlobDetails {Id = b.Id, .... };
    allBlobs.ToList();
    
    Michal Krawiec : Thank you. Doing this I have to implement IEnumerable interface into my BlobDetails class. I think I can do it ;-)
    Peter Lillevold : No, you won't have to implement IEnumerable. I extended the sample, but I guess you've already figured it out from @Marcs sample.
    Michal Krawiec : Yes I did :-) Thanks.
  • If BlobDetails isn't the LINQ entity, then you can do it directly:

    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();
    

    However; if BlobDetails is a LINQ entity, you need to use subtrefuge:

    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();
    

    The AsEnumerable breaks the LINQ composition, making it work.

    Marc Gravell : Note I'm not trying to translate Opis, Rozmiar, etc ;-p
    Michal Krawiec : BlobDetails is not a LINQ entity. It is just my class.

0 comments:

Post a Comment