Reputation: 27021
I'm using LINQ to SQL and have a database table called Product with 20 columns. The Product table is mapped to the Product class in the LINQ to SQL metadata.
I'd like to use my dbContext and retrieve some product records but only populating 10 columns not all 20 columns.
How would that be possible to specify which columns should be returned/populated with LINQ to SQL (or EF)?
I know one way would be using stored procedures but that's this question is about.
Thanks,
Upvotes: 0
Views: 92
Reputation: 47680
You usually use an anonymous class for that:
db.Products.Where(... filter ...).Select(item => new
{
Field1 = item.Field1,
Field2 = item.Field2,
});
Only the fields you include will be selected. If you intend to pass this data structure to other functions or return it, you need a concrete class definition for sub field set, such as:
class SmallerEntity
{
public something Field1;
public something Field2;
}
And you can initialize this in your Select statement:
db.Products.Where(... filter ...).Select(item => new SmallerEntity
{
Field1 = item.Field1,
Field2 = item.Field2,
});
I don't recommend the practice of half-populating an existing class. That makes your state space unnecessarily complex and allows more bugs in your code. Try to contain smaller subsets of data in their own classes.
Upvotes: 4