I need to write a Data Access Layer using Entity Framework. One of the requirements is to allow a configuration file to control where the data comes from. With one config setting it should come from a database; with another, from a web service.
Now, my initial thought is to have 3 DataAccess classes:
WidgetDataAccess
WidgetDatabaseDataAccess
WidgetWebServiceDataAccess
They would all implement the same interface. WidgetDataAccess would read the config and delegate to the correct child class. That seems sensible, right?
Is there any pattern that I should follow, or anyone with a better way to structure this?
Yes, Repository / UnitOfWork pattern.
Widget.Core : Your MVC application using only Widget.DAL namespace, dependency injected with either Widget.DAL.DatabaseService or Widget.DAL.WebService based on your config file
Widget.DAL : IRepository, IUnitOfWork, IWhateverYouNeed, DTOs
Widget.DAL.DatabaseService : Entity Framework Models and Context. Implementation of Widget.DAL interfaces using your Entity Framework context
Widget.DAL.WebService : Web client, Domain objects, implementations of Widget.DAL interfaces using your Web client
Related
I have just started to design a .NET library that is going to be used by either an application or a service (but this should not matter with 3-tier architecture?) and I'm struggling to find a proper separation of concerns and at the same time link DAL with BL in a proper way.
I was looking for tutorials, etc., but they all point to ASP.NET and Entity Framework, but I'd like to use ADO.NET (DataSets, DataTables) to build a library for desktop application / windows service usage.
Would anyone point me to a right direction by providing any sample/example implenentation or a tutorial/guide??
#EDIT
I was thinking about something like that:
DbManager - abstract class
XDbManager - X being a provider, SQL, etc. deriving from DBManager, being a singleton class (I'd prefer static, but these can't implement interface or derive from classes)
DbConnection - an object returned by DbManager method, containing methods for querying
BaseDbo - abstract class for Database Object
XDbo - X being the name of DBO, using DbManager => DbConnection to query (save, retrieve, retrieve sets, save sets? this is where I'm a bit confused, I need few persistent DataSets to save, update, retrieve data from tables - should they be implemented as Database Objects deriving from DataSets?)
BaseBo - abstract class for Business Object
XBo - business object class to handle and process data, etc.
Saying above I can't find a proper way to "link" both layers.
I also need to make use of SOAP web service in here, should that be implemented on business layer? Or should I introduce a new sub-layer?
If your application is properly designed, using EF or ADO.Net shouldn't matter much: that's the point of the DAL abstraction. I.e. you'll still have a method such as:
public IEnumerable<User> GetAllUsers()
{
....
}
that will returns all of your users. How it's implemented (i.e. Entity Framework or ADO.Net) is not important. The only difference is that your DAL won't be able to return IQueryable<T> (i.e. deferred execution won't work, or you'll need another abstraction layer on top of ADO.Net).
Same as for ASP.Net vs Desktop application: this shouldn't vary much either. You should use WCF services instead of ASP.Net MVC controllers. Instead of directly calling the BL from your controller, you would call a method of a WCF generated client proxy.
Everything that you could read about 3-tier application should apply for your use case too.
Premise:
I am exercising Domain-Driven Design and I separate my solution into 4 layers:
Presentation Layer
An ASP.NET Web API 2 project for a RESTful API web service
An ASP.NET Web MVC5 project for a documentation and admin screens
Application Layer
A class library project responsible to take commands from presentation layer and consume any domain services
Domain Layer
A class library project that contains business models and logic
A class library project that contains the domain services
Infrastructure Layer
A class library project that contains all the concrete implementation, like dataq persistance using Entity Framework, logging using Log4net, IoC using Simple Injector, etc
The domain layer only has a set of repository interfaces defined for the aggregates and it's up to the implementation data access mechanism which exists in the infrastructure layer to hide the implementation details.
In this exercise, I decide to use Entity Framework Database first approach. And of course, there is a app.config in the infrastructure project that contains a connection string.
Problems:
Ok, I spend a great deal and time trying to separate all the concerns and to focus on domain models. In the presentation layer (i.e., the API and MVC projects), there is no direct reference to the infrastructure project. And IoC container has been setup so all concrete implementation of the required interfaces would be injected into controller constructors.
When I select, for example, the API project as start project and run it, I got
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code.
Additional information: No connection string named 'xxxxxx' could be found in the application config file.
Question:
Now I understand if I install Entity Framework into the API project, copy and paste connection string from the app.config of the infrastructure project into the web.config of the API project, things will work. But that breaks our original purpose of separating concerns, doesn't it? If we do that, then what's the point of using Domain-Driven Design and making the data access technology ignorance from the presentation layer?
The reason we don't directly reference direct implementation of data access technology (i.e. concrete implementations that use dbContext and Linq) is that we could easily switch the underground access technology to something else.
So what would be the proper way to do it?!!
I do not want to install Entity Framework in my presentation layer, nor copy the connection string everywhere. I want all the data access and concrete implementation of repositories exist in just one library.
The Entity Framework configuration must be in the project where it is being used. This doesn't mean it's going to break your layered structure or your separation of concerns.
Remove all entityframework elements from your app.config. Create your own connection string element and provide it to entityframework on app startup.
I have a Solution with one project is Entity Framework and have my ASP MVC project, I looking for some advice or opinion about the idea of create in top of my POCO objects and the DBContext, a Business Logic Layer with static classes that have the all the methods (example a ContactBLL class with GetContactByID, GetAllContacts, GetContactsByType) to allow the access to the model data and that can be accessed in the Controllers Actions. In that way I don't have to put the implementation code of this methods in Controller Actions methods, and it can be reusable invoking this methods in other Action Controllers. I will appreciate your opinion because it could guide me to respond a question I've asking to myself around a week based in the answer to this one (about where to define the DBContext and how use it).
You can create different projects according to core functionality.
Data Access Layer(DB context and repository etc.) you can make Project.DataAccess, it will have only db context class and repository.
Business Logic Layer(Project.Business) it will have business logic and make call to data access layer.
UI Layer(Project.WebUi) it is mvc project.
and so on.
for detail info you can see this http://prodinner.codeplex.com/ code
Create separate class library for your POCO,
then create another class library for your repository, this should
include only the interfaces needed for your repository
and the implementation will be on another class lib like Project.EF,
Project.NH which will include Entity Mapping, Migration, Repository
implementations. but in reality, chances are you wont be changing
your ORM lib once it was implemented because it will just cause you
a lot of headache(just my 2cents).
you'll create your business layer(class lib) and
web project as separate lib. Models folder of your MVC project will contain your ViewModels.
this is what Im using right now and of course not the best structure, it just something that Im happy with :). hope it helps.
In general, there are four standard projects in a ASP.NET MVC - Entity Framework solution. They are 1) MVC, 2) Core/Business Logic Layer(BLL), 3) Data Access Layer/DBContext (DAL) and 4) Common/Utility.
Standard MVC project consists three main elements which are Model, View and Controller. However, middle to complex solution usually cuts off the Model element from MVC project and moves it back to BLL, we call it as ViewModel(POCO). Following this structure, MVC project is now responsible for employ/use the services from BLL and control the UI through controller.
Business Logic Layer (BLL) is the core of implementing business logic. It is responsible for serving request from the MVC project and work with DAL to persist data. As said above, BLL is the place to define ViewModel, its relations as well interface/ abstract class to support implementing design pattern. Viewmodel(POCO) is likely mapping one-one to data entity at DAL but we do not use the data entity directly on View. Following this structure will help to increase the customization on ViewModel like adding constrains
DAL is the place for DBContext and its data entities.
Common project consist of shared functions like Logging which is used in 1) 2) and 3)
Please read more at
https://www.codeproject.com/Articles/70061/Architecture-Guide-ASP-NET-MVC-Framework-N-tier-En
https://chsakell.com/2015/02/15/asp-net-mvc-solution-architecture-best-practices/
I've been reading articles on StackOverflow and other sites all day about best architecture practices and there are just so many conflicting ideas and opinions.
I've finally settled on an approach, but I am having a really hard time deciding where to place the EF objects (DbContext, Fluent APIs, Seeding data, etc). Here is what I currently have:
ASP.NET MVC Project: The actual web project. Contains the standard views, controllers and View Models (inside a Models folder).
Domain Model Project: Contains all POCO classes that define the database (domain) objects. Currently, does not mention or reference any EF objects.
Service Layer Project: Contains service objects for each type of domain object (e.g., IProductService, IOrderService, etc). Each service references EF objects like DbSets and handles business rules - e.g., add a Product, fetch a Product, append a Product to an Order, etc.
So the question is, in this configuration, where do EF classes go? Initially I thought in the Service Layer, but that doesn't seem to make sense. I then thought to put them in the Domain Model Layer, but then it ties the Domain Models to EF, which is essentially a DAL / Repository. Finally, I thought about creating a separate DAL Project just for EF, but it seems like a huge waste considering it will likely have 3-4 files in it (DbContext and a few other small files).
Can anyone provide any guidance?
There is no need for Domain Model since it will be redundancy. EF classes directly can act as Domain Model and they are converted to View Models while sending it to View. EF can be separated into different class library. Most of them use repository pattern along with any ORM incase it would be easy if they go for replacement. But I've seen criticism over using repository pattern, check this out.
Here is what I do:
Data:
Has one class inheriting from DbContext.
It has all the db sets.
Overrides OnModelCreating.
Mapping primary keys and relationships.
Entities:
Has every POCO classes.
Each property is decorated with needed data annotations.
Services:
Each service has common methods (GetList(), Find(), Create(), etc.).
Business:
Called from clients, orchestrate using services to perform a specific task UserChangePassword (this will check if this can be performed, then perform the task, or return error/unauthorized statuses among many others to make the client shows the correct information regarding the task. This on my case is where I log.
Clients (Desktop/Web/Wpf/etc).
I'm not saying this is the best approach, I'm just sharing what's been working for me.
how we can create a generic data access layer that can be used by any asp.net application using different datasource provider or webservices?
Can we create data access layer for application that consumes webservice?
You might look into the Repository Pattern. Repository is a facade that presents persisted objects as though they are in a collection in memory. Whichever provider you choose to get data is hidden behind the Repository interface.
IRepository with LINQ to SQL
Code Project Tutorial
A sample by Fredrik Kalseth
You have plenty of options! :-)
You mention you want to use the data access layer (DAL) from asp.net and web services. No problem.
Basically, what you need to figure out is a basic design you want to follow, and encapsulate the DAL into its own assembly which can be used / referenced from various consumers.
There are numerous ways of doing this:
create a Linq-to-SQL mapping for your tables, if you're using SQL Server as your backend, and use the Linq-to-SQL entities and methods
create a repository pattern (for each "entity", you have an "EntityRepository" class, which can be used to retrieve entities, e.g. EntityReposity.GetByID(int id), or EntityRepository.GetByForeignKey(string fk) or whatever
use some other means of accessing the data (NHibernate, your own ADO.NET based mapper)
you could actually also use webservice calls as your data providers
Your biggest challenge is to define a standard way of doing things, and sticking to it.
See some articles - maybe they'll give you an idea:
Creating a Data Access Layer in .NET - Part 1
Building a DAL using Strongly Typed TableAdapters and DataTables in VS 2005 and ASP.NET 2.0
Try the tutorials at www.asp.net:
DataAccess
Woah, there are a ton of resources out there. Best advice to start is to find a pattern that you feel comfortable with and stick to it for the project, there is nothing worse then changing your mind 3/4 the way in.
One that I have found and like to use is the Repository or Provider patter. The Repository pattern just makes sure you have standard access to repositories, like your store catalog or CMS system. You create an interface that in my case expose sets of IQueryable the object or the data model are just standard c# classes with now extra fluff POCO (Plain Old CLR Objects).
public interface ICMSRepository {
IQueryable<ContentSection> GetContentSections();
void SaveContentSection(ContentSection obj);
}
Then just implement the interface for your different providers, like a LINQ to SQL context, making sure to return the POCO objects as queryable. The nice thing about this is that you can then make extension methods off of the IQueryable to get what you need easily. Like:
public static IQueryable<ContentSection> WithID(this IQueryable<ContentSection> qry, int ID) {
return from c in qry select c;
}
//Allow you to chain repository and filter to delay SQL execution
ICMSRepository _rep = new SqlCMSRepository();
var sec = _rep.GetContentSections().WithID(1).SingleDefault();
The nice thing about using the Interface approach is the ability to test and mock it up or dependency inject your preferred storage at run time.
Another method I have used and is used in the ASP.Net framework a lot is the Provider model. This is similar except instead of an Interface you create a singleton abstract class, your implementations on top of the abstract class will then define the storage access means (XML, Flat file, SQL, MySql, etc). The base abstract class will be also be resonsible for creating it's singleton based on configuration. Take a look at this for more info on the provider model.
Otherwise you can look at this similar question.
IRepository of T is general good approach. This Interface should expose GetAll, GetByID, Insert, Delete and Submit methods.
But it's important to keep your business logic out of Repository class, and put it to custom logic/service class.
Also, if you return IQueriable in your GetAll method, what you can often see in various implementation of IRepository, UI layer can also query against that IQueriable interface. But querying of object graph should remain in Repository layer. There's a lot debate around this issue.
Look at using the Interfaces:
IDbConnection
IDbCommand
IDbDataAdapter
IdataReader