Returning Data Objects from DAL - c#

What is the best practice to return data objects from Data Access Layers to Interface?
Currently, I have a layer that communicates with database and returns DataTable to business Layer and then Business Layer instatiates the Business Objects and returns to the interface. Isn't that pathetic or poor practise?
My questions are:
-What is the best way to return Data Objects from DAL?
-If the DAL shouldn't return Data Objects, then how do I get the data to interface for DataBinding?
This is not a problem but a best practice issue.
Thanks everyone in advance

Have you looked at the Repository Pattern?
http://msdn.microsoft.com/en-us/library/ff649690.aspx
http://martinfowler.com/eaaCatalog/repository.html

I'm not sure that the DAL shouldn't return Data Objects - there are many personal preferences and it depends on factors such as the scale of the application. In the majority of the (smallish) applications I build, I used a datareader in the DAL rather than filling and passing around DataTables. The DAL uses the datareader to populate business objects that are then returned as a collection to the service layer.
In a more complicated scenario where tables don't always equate to business objects, I've used the datareader to populate DTOs (Data Transfer Objects - very simply classes that just contain variables representing the table structure and no logic) that are returned as a collection to the service layer. The Service Layer constructs the business objects from one or more types of DTO.
I'm not saying this is a definitive answer though (The problem with 'best practice' questions!) but hopefully my experience can give an insight (In what to do or what not to do is debatable!). I am interested myself to see what answers others can contribute to this. I suppose one answer you'll likely get is to investigate the use of an ORM!

Related

Is it okay to convert a result dataset in database layer

I'm working on an ASP.NET MVC project in C# with an N-tier architecture.
A class (EmployeeRepo) in the database project has many functions.
Each function's natural result from the transaction is a dataset, but they are converted as per the need.
The return types are:
Dataset (with one or more tables)
DataTable
int
bool
Object (single employee)
List<Object> (list of employees)
Which is better among the two or is there a standard to follow:
Return the result as is without any conversion. The conversion should only happen at other layer and not in the database layer.
It is okay to convert the result in this layer before returning.
Return the result as is without any conversion. The conversion should only happen at other layer and not in > the database layer.
In my view, repository layer should only do one thing. And this thing is to query database without applying any business logic and return result. Why? There are some reasones such as:
it complies with Single Responsibility Principle of SOLID principles.
code becomes simpler
code becomes more reusable
class will have lesser size
easier to write tests
So all conversions are made in service layer.
In addition, it is not good idea to return Dataset (with one or more tables) or DataTable from repository. It is better to return IEnumerable<T>. I mean you should avoid to return IQueryable or DataTable from repository to avoid querying at service layer. There are many opinions about this. So you can choose what is better for you. Should Repositories return IQueryable? imho, repository should not return IQueryable as all query logic should be placed in one place and not scattered across services.
More over, I hihly recommend you to read this post about is it better to return the most specific or most general type from an action method?
Generally speaking, your repository layer will return entities and it is your service layer that will repackage those into a form appropriate for your application to consume.
Note that what constitutes an entity may differ from project to project. For instance, if you use Entity Framework then it uses ADO.NET under the hood but it packages the data into entity classes and returns those objects. You could, in theory, do the same but, if you do, I'd question why you're not already using EF or some other ORM. If you're going to use ADO.NET directly then you probably ought to be returning DataTables and/or DataSets to your service layer. You should certainly not do some of one and some of the other. Go all in with one or the other.
Part of the idea behind a separate repository layer is that multiple different service layers should be able to be laid on top and work seamlessly, so the repository layer should be pretty general, based on the data rather than the application. Conversions are going to require business logic and that belongs in the service layer.
I was debating whether to post this as an answer or vote the question as too opinion-based but I think that the roles of the various layers are well-enough accepted that it's not really opinion any more.
Ideally your repository layer returns data mapped to Domain entitites/Domain types.
So the repository implementation would convert from low level db/ado specific types to your DTOs / Domain Types.
This way, you keep your domain clean and don't let those db specific types trickle into your business domain.

Best pattern to implement Translators between DB type object to Business type object

Our project had implemented Entity framework and we were floating the entity object type across all layers. Due to the sheer size of those objects we have decided to have business entities and data entities. Now I am confused as in
1) Where to implement the translation of these objects
2) How i.e any patterns or practices which I should follow to get better results.
*Edited *
Thanks for all the replies I am looking into Automapper and found it might fit well. But instead of using a library I wanted to create my own translator which would seem like reinventing the wheel. But my thought is I would have a lot more control on things then.
So going back to the original quesiton
On which layer should I implement my translation i.e we have an N-tire app and there are two schools of thought one being we should have a business layer and treat it as a facade and implement all translation and other business logic there and treat all others layer as a dumb layer which have no knowledge about the other layers and keep minimum reference of them so the data layer would be throwing out the same data entities and can be reused in another project where the Business object are somewhat different then our current object. The second school of thought is that the data layer should be returning and accepting business entities which would restrict non-database developers from unnecessary call on the db layer to create a business entitie.
Any patterns which are there for such kind of translation libraries.
This sounds similar to the problem faced by many people when using the MVVM pattern in association with an ORM. Automapper (http://automapper.codeplex.com/) is a great library that provides clean, convention based translation between types.
Please take a look the following, it has a really nice overview of all of microsoft techs. It might be a bit complicated though but it shows the layers very nicely.
N Layer sample app
You can try DTO's and ValueInjecter if you are moving data over the wire, or the same tool if you use ViewModels to bind to Views ... AutoMapper is great too.

How to fill business object from dal

I'm returning DataTable in DAL. And I have a businessObject called Customer. Where should I fill this object? Should it be done in DAL? Or in my front-end app? or where? A little cofused.
If at all possible, you want to avoid returning DataTable in your DAL and instead return the properly filled business object. There are several tools that will help you with this, for example LINQ to SQL, Entity Framework, or (my current favorite) Dapper.NET (used by this very site). I like Dapper best because it's lightweight and works well with a Data Repository pattern, which I frequently use.
You could have a Base DAL, which returns DataTables. Then have an Upper DAL, which does the converting to and from entities, (this is what I tend to use)
You really shouldn't be referring to DataTables in your UI layer.
A half-way house that I have seen before is doing the 'object filling' within a method in the actual business object itself, but that doesn't allow you to switch out your DAL so easily.
When crossing domains like this, where the representation of the data is different in each, you need an integration layer that will take care of the mapping between both representations. Most ORM tools do that mapping for you automatically, though.
But to stick with your example, you could have a layer of mappers to do that. CustomerMapper would then map from the DataTable to the Customer, effectively bridging the two domain representations.
It should be done in BL or Business Logic layer.

.net, C# Interface between Business Logic and DAL

I'm working on a small application from scratch and using it to try to teach myself architecture and design concepts. It's a .NET 3.5, WPF application, and I'm using Sql Compact Edition as my data store.
I'm working on the business logic layer, and have just now begun to write the DAL. I'm just using SqlCeComamnds to send over simple queries and SqlCeResultSet to get at the results. I'm starting to design my Insert and Update methods, and here's the issue - I don't know the best way to get the necessary data from the BLL into the DAL. Do I pass in a generic collection? Do I have a massive parameter list with all the data for the database? Do I simply pass in the actual business object (thus tying my DAL to the conrete stuff in the BLL?).
I thought about using interfaces - simply passing IBusinessObjectA into the DAL, which provides the simplicity I'm looking for without tying me TOO tightly to current implementations. What do you guys think?
I don't think there is a simple answer to your questions because there are many options depending on the circumstances. I have found it helpful to read the two books below to help me understand the problems you describe better.
MS .NET: Architecting Applications for the Enterprise (Esposito, Saltarello)
MS Application Architecture Guide, 2nd edition.
The second book is available online. Look here.
I think it is OK to pass the Business object to the Data Access Layer. I think the BLL's job is just to work with its objects, to check if all rules are being followed, about what can be saved, by whom, on what fields, time, etc.
Once it has done that it should pass it to the DAL, and I think it is IT'S job to figure out how to convert what it got into something that can be persisted, but it wont check what is being persisted or read or by whom, it will just do it. This could be straight foward, a la linq, but if your logic mdoels do not match your data model 1:1, then the DAL should do all the conversion.
About tying your DAL to the stuff in the BLL, I think you should worry about the other way around, tying your BLL to your DAL. I would use an interface to represent your DAL (as in IRepository) that way you can make your BLL call any kind of persistance mechanism just by changing the type of IRepository it is using (extra points if you use IoC :P). The concrete classes that implement the IRepository would be tied to the business objects, but they have to know what is it that they are saving don't they? while the BLL does NOT have to know what is doing the saving.
To pass business object in the DAL is the simpler and fastest method. It works in small projects, but have same disadvantages:
1) Business Objects are part of BLL layer, and if you pass objects in BLL then DAL becomes dependent of BLL. low layer knows about upper one - this contradicts the idea of layers at all.
2) Business Object are usially very complex to save it directly in BD. In this case it is better to introduce new "Mappers" intermediate layer.
To overcome all these issues I usially make interface to DAL independent of Business Objects. I use "Row" classes instead - representation of one record in the database or XML. In .NET 3.5 linqtosql autogenerated classes can be used for this purpose.
If I was in your position, I'd probably use LINQ to SQL to define my data access layer - it'll save you lots of work maintaining all that SqlCeFooBar stuff and give you a designer (of sorts) for maintaining your database that you would otherwise lack, using SQL CE.
So in that case, I'd probably couple the business logic layer pretty tightly to the entities exposed by the L2S layer. The justification being that the entities are the business objects, albeit devoid of any services.
I probably wouldn't let the entities get as far up the hierarchy as the UI though. At that level, it makes much more sense to use a model specifically for the view - especially given that you're using WPF.
Of course, all of this depends upon the size and complexity of your application. I'm assuming it's a fairly small scale application (single user?) given that you're using SQL CE.

n-Tier Architecture Feedback Needed

I started my website, like stackoverflow, with a little technical debt that I'm trying to pay off. Being a contract developer, I've been in many places and see many different methods of achieving this result, but the way I'm going is..
Presentation (web)
Business Layer (old fashioned entity classes and BL layer)
Data Layer (DA classes to SQL Server via Stored Proc)
My question primarily concerns the Business Layer. Right now I have an Entity namespace and a BusinessLogic namespace.
The BL has a reference to the DA and the Entity.
The Entity has a reference to the DA
(The DA is "unaware" of the BL or Entity)
I really want all my churning of turning Data into Entities to occur within the BL -- thus the Business Logic. However, I want the Entity to be able to access the BL if need be -- and thus remove the Entity's reference to the DL.
So...
Is is "wrong" to have the BL and Entity objects within the same namespace so they can work together?
Essentially, I'm trying have an entity object like Employee (classic example, eh?) and have the Employee have a
public Hashtable[] SubordinateEmployees
property that returns a Hashtable of other Employee objects that report to this employee. But I don't want to load it until it's needed. So for most employees the property would never get accessed, but when it does, it self-loads with a call to the BL, which calls the DA.
Does the question make sense?
If so, does my solution?
Thanks so much in advance!
The usual way to deal with the kind of situation your example represents is with facades. Instead of trying to get the subordinate employees from the Employee object, you use a call to the business logic to get it.
hashtable = BL.GetSubordinateEmployees(supervisor);
That way you have a single point of access to the subordinates, and there is only one thing (the BL) accessing the data layer and creating Entities.
Let me see if I can show you a better way to think about this
you have your data access (sql server, mysql, flat xml files, etc.) all of this should be abstracted away nothing else in your application should care or know how you are getting your data, only that it dose, if anything else knows how you are getting your data you have a layer violation. if the DAL dose anything other then get data you have a layer violation. Next you implement a data access interface something like IDAL that your business layer uses, this is very important for making your code testable by forcing you to separate your layers.
Your data entities can be placed in the DAL name space or give them there own, Giving them there own forces separation. Data entities are dumb objects and should contain very little to no logic and are only aware of themselves and the data they have, THEY DO NOT CONTAIN BUSINESS LOGIC!, DATA ACCESS LOCIC, OR UI LOGIC. if they do you have a layer violation. The only function of a data entity is to hold data and be passed from one layer to the next.
Biz layer implements a data access interface like the IDAL we talked about before you can instantiate this with a factory, an IOC container, or all else failing a concrete type, but add a setter property so this can be changed for testing. The Biz Layer Only handles Business logic, it doesn't know or care where the data came from or where it's going, it only cares about manipulating the data to comply with business rules, this would include date validation, filtering (part of this is telling the DAL what data it needs, let the DAL figure out how to get it). Basically the BIZ handles all logic that isn't UI related or Data retrieval related. Just like the DAL the Biz should implement an Interface for the same reason.
The UI layer Accesses the Biz layer the same way the Biz layer accesses the DAL for the same reason. All the UI layer cares about is displaying data and getting data from the user. The IU Layer should not know anything about the business rules, with the possible exception of data validation required to populate the Data Entities.
The advantage of this architecture is it forces separation of concern making it easier to test, more flexible, and easier to maintain. Today you are building a web site but tomorrow you want to allow others to integrate vi a web service, all you have to do is create a web service that implements the IBIZ interface and your done, when you have to fix a bug in the BIZ layer, it's already fixed in both your website and web service.
Taking this to the next level, lets say you are doing a lot of heavy number crunching and you need more powerful servers to handle this so all you have to do is implement an IDal and IBIZ interface that are really wrappers to WCF that handles the communication between your servers, now your application is distributed between multiple server and you didn't have to change your code to do it.

Categories

Resources