Connection design issue in Dapper, UoW, Generic Repository and multiple databases - c#

I'm trying to build a repository layer for an application which interacts with 3 databases, all MSSQL. I made the repository structure is based on Dapper and Unit Of Work Pattern and looks like below:
Is this a good design? or what could be a better design for this?
I do not want to pass the connection instance from business, as it's not the job of a business layer; and should be of the data layer itself. Currently, am trying to manage the connection within the UnitOfWork class with the connection name and would like to change it.
EDIT: The design is not possible as it has multiple class inheritance, which is not possible in c#. Are there any alternate solutions?

There's very little info to work with here, but I'll try. It doesn't matter how many db you're using or their type. The repository with UoW is an anti pattern which becomes even worse with multiple dbs.
A repository should work with whole concepts (aggregates). I'm going the DDD route because is the easiest way to model things in an app. A repository will take care of one aggregate type. Its implementation will use dapper to work with the db.
If you need to modify multiple aggregates in one operation, first do make sure the business process is modeled properly (usually it's not). The business process itself is the UoW but this implies using Domain Events and a durable service bus (to be server crash resilient). And every message handler should be idempotent.
A repository should never know about other repos and the inheritance part is mostly a dubious design. The UoW inside the repo which enables the persistence of the whole aggregate regardless of how many objects it's made from, is the db transaction. Don't complicate your life with distributed transactions, keep a transaction per db.
That being said, it's obvious that a proper architecture (it has very little to do with the repository pattern, even less with dapper) needs someone with a lot of experience if you want a maintainable codebase. If you're a junior, ask a senior or take some time to learn DDD modelling properly. It's very easy to come up with 'solutions' that seem simple enough but are an unmaintainable mess.

Related

Design of Data Access Layer with multiple databases

I have read many posts concerning the issue of having several databases and how to design a DAL efficiently in this case. In many cases, the forum suggests to apply the repository pattern, which works fine in most cases.
However, I find myself in a different situation. I have 3 different databases: Oracle, OLE DB and SQLServer. Currently, there exists a unique DAL with many different classes sending SQL queries down to a layer below to be executed in the corresponding database. They way the system works is that two of the databases are only used to read information from them, and the other one is used to either store this same information or read it later on. I have to propose a better design to the current implementation, but it seems as if a common interface for all three databases is not plausible from an architectural point of view.
Is there any design pattern that solves this situation? Should I have three different DALs? Or perhaps it is possible (and advisable) to apply the repository pattern to this problem?
Answers to your question will probably be very subjective. These are some thoughts.
You could apply command-query separation. The query side integrates directly with your data layer, bypassing any business or domain layer, and the returning entities are optimized for read and project from your databases. This layer could also be responsible to merge results from different database calls.
The command side consists of command handlers, using domain or business entities, which are mapped from your R/W database.
By doing this, the interface that you expose will be more clear and business oriented.
I'm not sure that completely abstracting out the data access layer with custom units of work and repositories is really needed: do the advantages outweigh the disadvantages? They rarely do, because you will you ever change a database technology? And if you do, this probably means a rewrite anyway. Also, if you use entity framework code first, you already have unit of work and an abstraction on top of your database; and the flexibility of using LINQ.
Bottom line - try not to over-engineer/over-abstract things; or make things super-generic.
Your core/business code should never be dependent on any contract/interface/class that is placed in the DAL layer of the application.
Accessing data is something the business/core layer of your application needs to be able to do, and this it should be able to do without any dependency of SQL statements and without having any knowledge of the underlying data access technology.
I think you need to remove any "sql" statements from the core part of the application. SQL is vendor dependent and any dependency to a specific database engine needs to be clean out of you core, and moved to the DAL where it belongs. Then you need to create interfaces that resides outside of the DAL(s) which you then create implementation classes for in one or many DAL modules/classes. Your DAL can be dependent of your core, but not the other way around.
I don't see why the repository layer can't be used in this case. When I have a database which I can only read from, I usually let the name of the repository interface indicate this, like ICompanyRepositoryRead.

Do I neet Unity of Work and Repository patterns when working with Entity Framework?

So at my job I was pointed to http://www.codeproject.com/Articles/990492/RESTful-Day-sharp-Enterprise-Level-Application#_Toc418969121 and was told to learn these patterns and implement them in my solution.
What confused me was that these things were before entity framework 6 and from what I understood, Unity of Work is used to optimize database performance by grouping queries together. Since EF6 has already these optimizations, should I still implement these layers? I get that the layerness helps with modularization and switching of data source. Does that mean that EF6 is too complex to implement with these patterns and should ADO.Net be used directly or something like that?
EDIT: I've noticed that this added layer allows usage of mock data sources. Not sure how useful this is because of the need to add another layer of apstraction
"Unit of Work is used to optimize database performance by grouping queries together." - This is not correct. Unit of Work is there to collect related operations together into a single transaction which is then committed or rolled back as a whole. It tracks changes made to objects so that required database operations can be deduced automatically and performed on your behalf.
When you work with Entity Framework, you use it to create DbContext from model. That class is both the Repository and Unit of Work, so you don't have to do anything special. Things only become more complicated than that when your project becomes so large that DbContext becomes more of a burden.
Repository is used to abstract your application from datasource, but since EntityFramework implements this pattern by itself and gives you a possibility to change data source seamlessly, there is no neccesity to add one more layer of abstraction.
You will just limit EF possibilities, while creating something like GenericRepository<T>. And nevertheless you won't be able to replace EF by another library with no changes to your code, even if you implement such a layer. (Some queries written for EF will fail for NHibernate, for example).
Just don't use DbContext everywhere in your application (inside UI code at least), use it by your data access layer (services with business dependent methods or something in that way).
Even for scenarios, where some cloud data storage is used (which EF won't be able to handle seamlessly), there is no neccessity for that layer, it's better to introduce separate classes and use them explicitly, because you cannot fit db and cloud interaction into one abstraction, it will start leaking at some point.
Entity Framework is a UnitOfWork/Repository pattern itself. If you need to abstract yourself from EF, then you could implement a layer on top of EF with your own UoW/Rep pattern.
This is good if you want to replace EF at some point in your proyect.
The cons? I think that building a UoW on top of EF gives you a redundant architecture and you will end up writing more code for something that maybe will never change.
In my current proyect, the main structure is very common, with a Data layer (with a sublayer for the Entities) for EF, Logic layer (where I put all the Business Logic) and the View layer (It can be web, or whatever). With that structure I directly invoke EF in the Logic layer.

Data from Database Using MVP-VM Design Pattern

In my quest to understand MVP-VM design pattern in preparation for a new project which will be using DevExpress, I am unable to find an example with a database example.
Viewing DevExpress, I am unable to locate an example with this design pattern.
So, my question is this, does anyone who has experience of this design pattern, if you have experience of this with DevExpress even better, can give me an example of database connection, mapping data from a database (query/table) to model, and saving data to the database?
I appreciate this may sound rather an elementary question, but I do not know with this pattern what is the best practice for taking data from the view to persist to a database, and vice versa. Therefore, I do not wish to go off and doing incorrect.
Thanks
Classic architectures define the following parts:
DAL (Data Access Layer) : Deals with db operations, contains no business logic.
BLL (Business Logic Layer) : Deals with business logic and constraints, but no database operations.
PL (Presentation Layer) : Deals with presentation and user interaction.
MVP/MVVM deals with PL only. The big question is, what exactly is the M(odel) in this patterns. One example is using Entity Framework or DevExpress XPO to map objects to the database. But what are this objects? Are they the VMs? Are they the Model(s)? Or are they just simple Dtos of the Dal? If you look at the previous definitions, the last one will be the most matching one. But that means you have to map this dtos to you model objects (where the logic resides) and to you vms (where the databinding happens) or first to your model and in a second step from there to your vms? What about the filtering/sorting/paging capabilities of the datagrid, that only works if you give it direct access to you dal?
In my opinion true separation of the three aspects could only be achieved with CQRS or similiar architectures. At least I don't know of others. But this is only for extreme complex applications with lot of business logic and comes with much overhead and trade offs.
So, for your app, you have to decide which barriers you will break to suite your needs and to avoid needless complexity for your project. A simple CRUD application could use Entity Framework/XPO and use the objects directly as VMs for databinding. You have no bll at all. If it grows more complex you perhaps go a little bit in the direction of cqrs. You define views and use EF/XPO and their objects directly for databinding, but for complex operations you create a bll (domain)model with objects (that are loaded with EF/XPO either) that execute theese operations (needing to reload you vms afterwards). And if it is even more complex, you could go the complete way to CQRS perhaps with event sourcing and perhaps modeling with DDD.

.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.

Design of Business Layer

We are currently revamping our architecture and design of application. We have just completed design of Data Access Layer which is generic in the sense that it works using XML and reflection to persist data.
Any ways now we are in the phase of designing business layer. We have read some books related to Enterprise Architecture and Design so we have found that there are few patterns that can be applied on business layer. Table Pattern and Domain Model are example of such patterns. Also we have found Domain Driven Design as well.
Earlier we decided to build Entities against table objects. But we found that there is difference in Entities and Value Objects when it comes to DDD. For those of you who have gone through such design. Please guide me related to pattern, practice and sample.
Thank you in advance! Also please feel free to discuss if you didn't get any point of mine.
#Adil, this is not an answer to your original question, but I would advise you to revise your decision to roll your own data access layer. You note that you'd like to go to NHibernate: just do it now.
IMO, writing an ORM is a waste of time unless you have some very specific restrictions. There are a wealth of options out there, with hundreds of hours of effort poured into them already. Leverage it! LINQ2SQL, Entity framework, NHibernate, Subsonic, LLBLGen are all good, and there are more out there.
Note too that if you roll your own you won't get to use the goodness that is LINQ without a lot of effort.
As far as layering goes, try not to go nuts: keep the number of layers in check and concentrate instead on building a worthwhile interface between them to guard against your abstractions leaking.
I've seen a number of very "patterned", beautifully layered projects that in use end up with logic everywhere and persistence abstractions leaked all over the place. Keep it simple!
CSLA.NET works pretty well as a base for the business layer.
#Adil,
I'm not very experient user, anyway, this is the kind of model I'm using (also with NHibernate).
GUI - with all the web forms and so on
BLL - The catalogs that are responsible for creating instances of new objects
DAL - The place where classes responsible for interaction with NHibernate are implemented. The NHibernate mapping files are here.
Model - Class Library that is used by the BLL and DAL for data transfer object between.
Different patterns are used. For example, the BLL and DAL have a Factory class that allow access to an interface. The catalogs are Singleton classes. All of the catalogs are accessible using a master Singleton class representing my business logic top object (for example "Enterprise" => "Enterprise.PeopleCatalog".
Anyway, hope it helped...
#AngryHacker, thanks for the tip, could you give an example of CSLA.NET?

Categories

Resources