teenup
teenup

Reputation: 7667

How to get a subset of columns from a table without requiring a new type in Linq

e.g. If I have the following class:

public class Schema
{
    public int SchemaId { get; set; }
    public byte[] XsdFile { get; set; }
    public byte[] MetadataFile { get; set; }
    public byte[] TemplateFile { get; set; }

    public string Name { get; set; }
}

And I use this query in Linq, I will get all the columns:

from s in db.Schemas select s;

If I need only the Id and Name column and default values for other three byte array fields, I will need to either project it to another defined type or anonymous type or dictionary like this:

db.Schemas.ToDictionary(s => s.SchemaId, s => s.Name);

But, How can I get the same type i.e. Schema itself with a LINQ query that will have default values of these byte arrays rather than fetching them from the table? I don't really want to create another type and I can't do with anonymous type because I want to transfer it from web service.

Upvotes: 0

Views: 75

Answers (2)

Wyatt Earp
Wyatt Earp

Reputation: 1823

Select the relevant pieces into anonymous types, call .ToList() to bring the data into memory, then project into new Schema objects.

var result = (from s in db.Schemas
             select new { s.SchemaId, s.Name })
             .ToList()
             .Select(s => new Schema
             { 
                 SchemaId = s.SchemaId, 
                 Name = s.Name,
                 XsdFile = new byte[length],
                 MetadataFile = new byte[length],
                 TemplateFile = new byte[length]
             });

Upvotes: 1

sgmoore
sgmoore

Reputation: 16067

Split the routine into two.

First use an anonymous type

var tempList= (from s in db.Schemas select new { s.SchemaId , s.Name}).ToList();

Then use the temporary List to create objects o type Schema

var results = (from s in tempList 
              select new Schema { Schema = s.SchemaId , Name = s.Name }
              ).ToList();

Upvotes: 0

Related Questions