DAL design question - c#

I need to design a Data access layer DAL .Net Enterprise library version 3.5 Data access application block (DAAB)
In my application,I've various logical modules like Registration, billing, order management, user management,etc
Am using C# business entities to map the module objects to database tables and then return the List collection to the client.
I would like to design my DAL in such a way that if tomorrow we decide to use some other data access framework we should have minimal code change.
Given this, how do i design my class structure?
I thought I would have a class DbManagerBase which would be a wrapper over existing .net DAAB
This class DbManagerBase would implement an interface called IDbManagerBase which would have public methods like ExecuteReader, ExecuteNonQuery, etc.
The client class ie. RegistrationDAL,UserManagermentDAL would have the following code inside each of its methods:
IDbManagerBase obj= new DbManagerBase()
obj.ExecuteReader(myStoredProcName)
.
.
.
is this a good OOPS design?may i know any better approach please?or do i need to use inheritance here?
Can i have all the methods in DbManagerBase class and RegistrationDAL,UserManagermentDAL classes as static?I guess,if i've methods as static then the above interface code wont make any sense...right???

To truly abstract the DAL I'd use the repository pattern.

To answer a few of the questions:
Can i have all the methods in
DbManagerBase class and
RegistrationDAL,UserManagermentDAL
classes as static?
I would probably go with a non-static approach cause it gives the flexibility to better control instantiation of the DALs (eg. you could create instances of them from a factory), also it will allow you to have two DALs in place that are talking to different DBs in a cleaner way. Also you will not need to create an instance of the DbManagerBase in every object since it would be an instance member.
Regarding IDbManagerBase having ExecuteReader, ExecuteNonQuery and obj.ExecuteReader(myStoredProcName)
I would be careful about baking the knowledge about database specific concepts in too many places. Keep in mind some DBs to not support stored procedures.
Another point is that before I went about implementing a DAL of sorts I would be sure to read through some code in other open source DALs like NHibernate or Subsonic. It is completely possible they would solve your business problem and reduce your dev time significantly.
If you are looking for a small example of a layered DAL architecture there is my little project on github (it is very basic but shows how you can build interfaces to support a lot of esoteric databases)

Related

Should I create namespaces for Entities and Value Objects?

I am building an application using DDD principles. I am now thinking about the namespace structure in the core of my application. Please see the idea below:
Company.Application.Core.Entities
Company.Application.Core.ValueObjects
However, I cannot find a single example of an application on GitHb, which follows this convention. Is there a specific reason not to follow this naming convention?
I also have a base class for entities i.e. Company.Application.Core.Entities.Entity and a base class for value objects i.e. Company.Application.Core.ValueObjects.ValueObject
The alternative option is to put all Value Objects and Entities in: Company.Application.Core
Your approach will work, but such composition tells story about your code focused on DDD Building Blocks, not about immanent features of your domain. In DDD we want to show important things about domain, the technology issues are not the most important concerns anymore.
I suggest creating following namespaces:
YourCompany.YourApplicationName.YourParticularBoundedContextName.Application
here you can keep all Application Scope building blocks i.e. Application Services and DTO's which are used to transfer parameters to Application Services and return data from them.
YourCompany.YourApplicationName.YourParticularBoundedContextName.Domain
this is the namespace where you will create subnamespaces for Domain Scope building blocks.
YourCompany.YourApplicationName.YourParticularBoundedContextName.Domain.AggregateName
each Aggregate have its own namespace in which there are Aggregate Root class, Entities and VOs used internally in this Aggregate, Repository interface, Aggregate Factory if needed etc.
I don't know if in C# it is possible, but in Java there is another advantage of having separate package (namespace) for Aggregate - you can make Aggregate Root class public and all other Entities and VOs that are internally used as package scope, so they will not be visible outside package (namespace). This way you build public API for your Aggregate that no one can break, because there is a guardian: the compiler :)
YourCompany.YourApplicationName.YourParticularBoundedContextName.Infrastructure
here is a place for repositories' implementations (each in subnamespace of corresponding Aggregate)
Base classes can be kept in:
YourCompany.YourApplicationName.Domain
and even kept in separate project as you can try to reuse it in another application.
What is the advantage? When working with code you are focusing on features and domain rather than on technological aspects. You will more frequently have to cope with problems like "how does this process flow look like" than "I want to see all my Entities and VOs at once", so let your code structure support this. Separating Entities (Aggregates parts actually) and VOs (also Aggregate parts) into separate namespaces you lost information what is working with what. You can simple end with big ball of mud, because you will reuse something that shouldn't be reused.
Please look at:
https://github.com/BottegaIT/ddd-leaven-v2
it is a sample project in Java with packaging done this way. Maybe it will help you.
Another example is:
https://github.com/VaughnVernon/IDDD_Samples
which is a sample for Vaughn Vernon's book about DDD.
There is also article that can be useful:
http://www.codingthearchitecture.com/2015/03/08/package_by_component_and_architecturally_aligned_testing.html
Using separate namespaces for your Entity types (that map to database tables etc.) and your DTO types (used for passing data between client and server layers of your application) is pretty standard practice, even if .Entities and .ValueObjects aren't particularly common choices. I don't think it's worth worrying about too much as long as you use them consistently.

Good Generic Repository Pattern when not Using Code First

I'm trying to wrap my head around repository pattern and dependency injection concepts for my ASP.NET MVC applications.
I ran across the article Repository Pattern with Entity Framework, and really liked how simple the code is. There doesn't appear to be that much code and it's all completely generic. That is, there's no need for multiple repositories for the different objects in the database as most people appear to be doing. This is just what I want.
However, the code is written for code first, which I'm not planning to use.
Questions:
Is there a good reason why the same code couldn't be used for applications that don't use code first?
Can someone recommend a better approach for my applications that don't use code first? (Keeping in mind that I'm absolutely sold on this generic pattern.)
Any other tips to help me move forward?
You can make a repository interface for any underlying data store. You can simply define an interface like so:
public interface IRepository
{
IQueryable<T> GetQueryable<T>();
void Insert<T>(T item);
}
Then, you can implement a class behind this which will implement it. It doesn't have to be code-first; you can back it with an ObjectContext created from an EDMX file, for example.
The key here is in creating the right abstraction. You can easily do that with an interface, and then implement it however you want behind the scenes.
Because you're using dependency injection, the implementation doesn't matter as much, as long as you've defined the contract correctly, the implementation (and testing of it) should be simple. And if it doesn't work, or you want a different data store altogether, you just tell your dependency injector to use a different implementation, the contract doesn't change.
The same can be said for any abstraction you create; you can have an interface that reads and writes data (like the article you reference does), you just have to pull the abstraction out.
Have a look on this. I think this link will help you most
http://www.codeproject.com/Tips/572761/Generic-repository-pattern-using-EF-with-Dependenc
In this link Generic repository pattern is used with dependency injection in MVC project without using code first approach.

Proper way to structure my classes

Gday guys.
Clearly im an amateur at programming, but am learning!
I want to create a simple asp .net web site that basically is a very small database for repair jobs that we have going on in our office.
I am uncertain of a few things:
Firstly, how do I structure my classes?
I know I will have a job class that will have properties such as name, issue description, technician etc and also have methods for loading certain jobs into that instance. But if I have a page that will search for all jobs, where abouts would that method that returns ALL jobs lie? I can't really see it going into the Jobs class, as the Jobs class really only deals with a single instance of a Job, and not multiple jobs. Do I have to have a separate class called Jobs that has the methods for getting ALL jobs?
Second question- if I have methods that retrieve data from a database, what is the best type to return this to the calling class? A List? A DataSet?
Finally, should I again have a separate class for the data access and a separate class for the business logic type stuff for Job?
I know I might be looking into such a simple application too much here, but I want to get myself into the habits of using the RIGHT techniques from the start..!
Looking forward to haering your advice!
Visual Studio provides sample projects, that you can create by using the New Project option... It can create a fully working web application, so that you can start learning from it.
You can try MVC. Create a new MVC project and it will ask if you want it to be empty, or if you want to create a sample project with working code... of course you should take the second choice... after that you can run the application and see what happens! =)
Then you can start exploration... try changing things in this project. And question about everything you don't understand. StackOverflow is a good place, as you may have noticed.
1) Refactoring by Martin Fowler realy helped me grasp OO programming. It can teach you not only to refactor your classes, but what to look for when designing them.
In your example, the method that returns all jobs will go in to the class that holds the list of jobs. Stay away from creating a List<Job>, create a single instance of a class that holds a List<Job>.
2) Stay away from DataSets unless you know exactly why you need to use one. I suggest you use WCF + Linq to fetch data from your database as a list of your own class.
3) WCF + Linq will take care of your data access layer. Your own classes will be your busness logic layer. Finaly you will benefit from an addition View layer for your interface.
You need to separate repository class from entity class - make class have a single responsibility. That's basic OO principle.
list would be better and simple.
of course, you need to separate DAL and BL.
If you want right way to build a web site, be interested in MVC, TDD, Linq, ORM (e.g., EF), Dependency Injection, and other design patterns.

Is the DAO Pattern Widely Used in .NET?

Is the DAO—Data Access Object—a commonly used pattern in .NET? I've always used DAOs as a way to provide access to my data layer. For example I might have a thin interface over my EntityFramework ObjectContext exposing all of my ObjectSets as IObjectSet.
Complex queries would then be exposed by DAOs, each of which with a dependency on this interface. I might have a ProductDAO that exposes methods like GetProductsOnSale() or GetInfrequenlySoldProducts(). My controllers or presenters would then use these methods, which would likely be virtual to allow stubbing specific results for unit tests.
So is this a commonly used idiom in .NET? For some reason the overwhelming majority of examples I see online using this pattern are based on Java. Even this question on DAO best practices is tagged as Java and not C#.
There's nothing wrong with using something from another community, I just have a slight fear that everyone around me is doing things differently...
It is a common idiom in .NET. I have used it and have seen it used in many places.
It is built into the framework - see the System.Data namespace - many of the classes are base classes for specialized providers (SQL Server, Oracle, MySQL etc...) and operations are executed on the base classes.
However, what you are describing sounds more like the Repository Pattern to me, not simply the use of Data Access Objects.
This is also used in many projects, though is not built into the framework.
I use the DAO pattern extensively.
You mentioned the Entity Framework; to that I would add that I find DAO much better than DataSets and DataTables, which are too much like a database an not enough like an object for my tastes. For example, DataRows can't be added to more than one data table, so I can't pass around subsets of the loaded data to different objects without moving them to a container that wasn't built to contain them. (I.e., it seems like a DataRow should be in a DataTable, but they can only be in one DataTable at a time.) DataRowViews are clunky and not nearly as intuitive as adding entity objects to another list.
My biggest recommendation on the usage of the Repository pattern for encapsulating data access (which indeed is a very good pattern), is to be able to create a generic repository. But to create a very smart generic repository that gives you basically live wiring to immediate access to all standard CRUD operations, along with access to the complex query construct that you won't expose past you ISomeService facade.
The most important thing about using a generic repository, is you want it to be based on constructor injection and not based on inheritance. This way you can compose your SomeService to be dependent on many generic repositories that it would need to fulfill a meaningful business domain boundary.
I wrote an indepth blog on this concept. Creating a common generic and extensible NHiberate Repository version 2. While this blog post is specific in reference of NHibernate you can take the same core concepts and apply them to almost any DAO.
Note with some tools, like Entity Framework, Linq2Sql and RavenDB to name a few, they expose very refined repositories themselves and might not necessarily benefit from adding an additional wrapper.

Design patterns advice - separating ViewModels from domain models

I need to separate ViewModels in my MVC project from my business models (Data access layer) which lives in a separate library.
Assume that I have Database Access Layer classes in a separate library. Our primary project (MVC) does know nothing about those classes and they talk to each other through an Interface. It’s easy enough to use IOC and resolve dependency injection using Ninject or something, right?
Now DataAccessLayer contains class named Car with properties Engine and Wheel. In my MVC project (which doesn’t know nothing about DataAccessLayer and its classes) I need to use some Car objects. So I have another Car class (it’s just a pure ViewModel) and it has the same properties – Engine and Wheel (of course in real app there will be some differences between model and viewmodel, for the sake of simplicity let’s ignore that)
IDataAccessLayer Interface has a method called IEnumerable GetAllCars() that returns list of DataAccessLayer.Car objects.
Now I need to create MVCProject.Car collection, iterate through IEnumerable which was returned by GetAllCars(), on every iteration I need to create a new MVCProject.Car object, populate Engine and Wheel properties, and finally add that object to the Collection.
So: everytime I have to create almost the same structures and somehow manage them in different places.
Here is the problem, see? Or it isn’t? I feel like it will end up into big mess if I don’t change that. Don’t repeat yourself principle violation as it is. Tell me please how to make it right. Using I don’t know proxies or prototypes or maybe some other design pattern which I suck anyway. Or some sort of a tool like Ninject (which I only know how to use as IOC container) or Automapper or whatever, which I probably will suck even more than I suck in design patterns.
I also don't see much of a reason to keep the DAL separate from the MVC layer. In case you're interested, here is the layout that I've used for multiple project and I find it is very usable and flexible.
DataObjects
Basic objects with only properties. Also includes enumerations which the DataObjects use.
DataAccess
Inherit from DataObjects and add GetByPrimaryKey, GetByForeignKey, GetByUniqueIndex, GetAll, etc., etc. Also contains the Caching layer where you would find StateCache, CountryCache, etc. for quick access to frequently used things. The "GetBy" methods will utilize the caching layer whenever possible.
Logic
Static classes, one for each DataObject\Access type. Includes logical work other than simple fetches as detailed in the DataAccess layer.
Web\Front-end
UI works with DataAccess and Logic layers to get and update objects as well as call other defined logical APIs.
I use my own custom-made code generator to generate 98% of this code (except the UI layer).
It sounds like your MVC library should know about your data-access library, shouldn't it?
Or, if you really want to keep your MVC and DAL libraries separate, you could always add a third library with references to both MVC and DAL. Then it could handle retrieving cars from the one library, and converting them to the other.
But again, I don't see why your controllers (or ViewModel, from what you've described) shouldn't have access to the DAL. Your car ViewModel would retrieve instances of Cars from the DAL, and go from there. So long as the way in which it receives the cars is coded through an interface, you should be able to stub that out later for your unit tests.
EDIT
So it looks like you think you'll be changing the entire DAL around later, and you want to minimize the difficulty of that? If that's the case, you might look at the adapter pattern. You would pass all your DAL objects to adapters, which would return to you objects in your business layer. Then, if your DAL changes, you just update your adapters.
I found a way to make it really ugly :)
The Goal: Caller doesn't know nothing about Model Entities at DataAccessLayer, and gets all the data through the interface.
How to get the data without manual mapping between Model and Viewmodel?
Through reflection.
public IEnumerable<T> GetCars<T>()
{
var lst = new List<T>();
_data.GetTable<Cars>().ToList().ForEach(x =>
{
var newCar = Activator.CreateInstance<T>();
typeof(T).GetProperty("Engine").SetValue(newCar, x.Engine, null);
typeof(T).GetProperty("Wheel").SetValue(newCar, x.Wheel, null);
lst.Add(newCar);
});
return lst;
}
It Works. But the biggest question here is it fair and considerable architectural decision? How the performance will be affected in a real life app?

Categories

Resources