Reputation: 696
Linq / Linq-to-Sql / C# newbie question, but I can't seem to find any useful information on it. It is possible I'm not phrasing the question correctly. Any help appreciated.
So, I have some existing Database tables, and I have generated the DBML file from them. I have the partial classes and the DataContext. How can I connect my Entity classes back to this?
Am I just missing something very obvious?
Thanks
Upvotes: 0
Views: 177
Reputation: 152521
If you want to keep your Entity classes separate from your partial DAO classes (which is a good thing for non-trivial applications), the most straightforward way is to create a mapping layer between the two (e.g. PropertyA
in your DAO class is mapped to PropertyB
in your Entity class).
If most of the field names/types are identical between the two layers, one way to save a lot of redundant coding is to use a mapping library like AutoMapper. It handles identical properties easily and can be configured to handle non-identical properties without too much effort in most cases.
In an MVC project I typically do this in the Repository. I will have Map()
functions that take one type of object and create another. For example, to map a data-layer Order
class to a domain-layer Order
class:
public Domain.Order GetOrder(int orderID)
{
Data.Order order = context.Orders.Where(o => o.OrderID = orderID); //
Domain.Order newOrder = Map(order);
return newOrder;
}
public Domain.Order Map(Data.Order order)
{
if (!UsingAutomapper)
{
// raw way
Domain.Order newOrder = new Domain.Order
{
ID = order.OrderID,
Number = order.OrderNumber,
OrderDate = order.OrderDate
};
return newOrder;
}
else // let AutoMapper do the dirty work
{
return Mapper.Map(order);
}
}
Upvotes: 2