I’ve been noticing when I pull things out of the my MSSQL db using LINQ-to-SQL using something simple like:
public IEnumerable<Contact> GetAll()
{
var Contacts = from c in _context.Contacts
select new Models.Contact
{
ContactID = c.ContactID,
FirstName = c.FirstName,
LastName = c.LastName,
Email = c.Email,
Phone = c.Phone,
Address1 = c.Address1,
Address2 = c.Address2,
City = c.City,
State = c.State,
Zip = c.Zip,
HighImportance = (bool)c.HighImportance,
PrimaryContact = (bool)c.PrimaryContact,
OfficeLocation = c.OfficeLocation
};
return Contacts;
}
I have a complex object (foreign key reference) to an OfficeLocations table which I would like to populate. If I do something like:
_context.OfficeLocations.SingleOrDefault(ol => ol.OfficeLocationID == c.OfficeLocationID);
Then this returns the type which is generated by my DBML. Up to now I’ve been using something like:
OfficeLocation = new OfficeLocation
{
OfficeLocationID = c.OfficeLocationID,
Name = c.OfficeLocation.Name,
Phone = c.OfficeLocation.Phone
}
But I feel like there should be a much better way to do it, maybe by using extension methods on my DBML data objects or something?
Any thoughts would be greatly appreciated.
Thanks!
You should checkout AutoMapper. It’s a very good library that would help you setup mapping between objects in your application. For example, you might have domain entities and a layer of DTO’s; then you can use AutoMapper to map from your entities to the corresponding DTO’s, which I assume is what you’re looking to do.