LinqToSql: How can I create a projection to adhere to DRY?
- by mhutter
Just wondering if there is a way to take some of the repitition out of a LINQ to SQL projected type.
Example:
Table: Address
Fields: AddressID, HouseNumber, Street, City, State, Zip, +20 more
Class MyAddress: AddressID, HouseNumber, Street (Only 3 fields)
LINQ:
from a in db.Addresses
select new MyAddress
{
AddressID = a.AddressID,
HouseNumber = a.HouseNumber,
Street = a.Street
}
The above query works perfectly, and I understand why something like this will return all 20+ fields in each row:
from a in db.Addresses
select new MyAddress(a);
class MyAddress
{
public MyAddress(Address a)
{
this.AddressID = a.AddressID,
this.HouseNumber = a.HouseNumber,
this.Street = a.Street
}
}
Which leads me to my Question:
Is it possible to implement some kind of helper function or extension method to "map" from the LINQ model to MyAddress yet only return the necessary fields in the query result rather than all of the fields?