In what scenarios would i want to create custom business objects from Linq to Sql results?
-
01-10-2019 - |
Pergunta
A simple linq to SQL query Might return a product object. Obiously I could pass this object to my business layer, then read and update the data, directly against that object.
I've seen a bunch of implementations where following the execution of the linq query the resulting object is mapped (via automapper or manually) to a custom business object. So in the case of product where I might have the linq object:
product.ProductId and Product.ProductName
and then I would define a custom Product business object like so:
class BusineszProduct
{
string ProductId;
string ProductName;
}
and some simple mapping code like:
BusinessProduct myProduct = new BusinessProduct(); myProduct.ProductId = product.ProductId; myProduct.ProductName = product.ProductName;
and then pass myProduct around my business layer, modify it, read it and so on, then later update the linq object.
In what scenarios would I want to create the custom BusinessProduct class?
Solução
IMHO, the general reason is to decouple / disentangle your Business Entities from the Linq2SQL ORM baggage that comes with Linq2SQL Entities
However, in an extreme scenario, you may have multiple mappings:
- Linq2SQL entities for the "Data Access" Layer - however these are tightly coupled to the L2S DataContext
- POCOs / Business Entities would be used for business rule application, validation etc
- If you are using Web Services or WCF, you might also represent the data as Message Entities e.g. if you need to present the entities in a very specific format when they are serialized across the wire
- And finally, if you have a MVC / MVP / MVVM UI architecture, you might want entities tailored for your views
Outras dicas
In my application, I do a Linq query which joins six different tables, and provides a couple columns from each one. There is no table-specific object type which matches that set of information. Hence I create a custom business class to handle the record set.
You can view it yourself (at http://www.njtheater.org)
I select from the Productions
table by Date. It joins to the Play table (where I get the Title & Description), the Troupes table (where I get the theater company name), the Venues table (where I get the theater name & City). The Plays table joins to the PlayCredits table which joins the People table (where I get the playwrights' names)