Is ok to have Entity Framework inside Domain layer? - c#

I have a project with the following structure:
Project.Domain
Contains all the domain objects
Project.EntityFramework, ref Project.Domain
Contains Entity Framework UnitOfWork
Project.Services, ref Project.Domain and Project.EntityFramework
Contains a list of Service classes that perform some operations on the Domain objects
Project.Web.Mvc, ref to all the projects above
I am trying to enforce some Business rules on top of the Domain objects:
For example, you cannot edit a domain object if it's parent is disabled, or, changing the name of an object, Category for example, needs to update recursively all it's children properties (avoiding / ignoring these rules will result in creating invalid objects)
In order to enforce these rules, i need hide all the public properties setters, making them as internal or private.
In order to do this, i need to move the Project.Services and Project.EntityFramework inside the Project.Domain project.
Is this wrong?
PS: i don't want to over complicate the project by adding IRepositories interfaces which would probably allow me to keep EntityFramework and Domain separate.

PS: i don't want to over complicate the project by adding IRepositories interfaces which would probably allow me to keep EntityFramework and Domain separate.
its really a bad idea, once i had this opinion but honestly if you dont program to abstraction it will become a pain when the project becomes larger. (a real pain)
IRepositories help you spread the job between different team members also. in addition to that you can write many helper extensions for Irepository to encapsulate Different Jobs for example
IReopisotry<File>.Upload()
you must be able to test each layer independently and tying them together will let you only do an integration tests with alot of bugs in lower layers :))

First, I think this question is really opinion based.
According to the Big Book the domain models must be separated from the data access. Your domain has nothing to with the manner of how storing the data. It can be a simple text file or a clustered mssql servers.
This choice must be decided based on the actual project. What is the size of the application?
The other huge question is: how many concurrent user use the db and how complex your business logic will be.
So if it's a complex project or presumably frequently modified or it has educational purposes then you should keep the domain and data access separated. And should define the repository interfaces in the domain model. Use some DI component (personally I like Ninject) and you should not reference the data access component in the services.
And of course you should create the test projects also using some moq tools to test the layers separately.

Yes this is wrong, if you are following Domain Driven Design, you should not compromise your architecture for the sake of doing less work. Your data-access and domain should be kept apart. I would strongly suggest that you implement the Repository pattern as it would allow you more flexibility in the long run.

There are of course to right answer to whats the right design...I would however argue that EF is you data layer abstraction, there is no way youre going to make anything thats more powerful and flexible with repositories.To avoid code repetition you can easily write extension methods (for IQueryable<>) for common tasks.Unit testing of the domain layer is easily handled by substituting you big DB with some in-proc DB (SqlLite / Sql Server Compact).IMHO with the maturity of current ORMs like nHibernate and EF is a huge waste of money and time to implement repositories for something as simple as DB access.
Blog post with a more detailed reply; http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer

Related

How to manage domain model or data access model or data transfer model

In DDD, many models are there:
Domain model, which is used in busiess or application layer.
Data access model, which is used in data access or data repository layer.
Data transfer model (DTO), which is used in presentation layer.
Beacuse of them, the disadvantages raiseļ¼š
They violate the DRY principle, beacuse many duplicate fields exist between them and can't avoid.
They need a lot of irritable mapping to conversion between different layers.
How can we reduce the irritable Models?
Ultimately, it is about choosing your battles. One of the main considerations in a Domain-Driven solution is that it is focused on isolating and encapsulation of the domain. That means that, by that very premise, you are not going to want to use it as an approach in every single project. You need to have an inherent complexity that you are trying to reduce, and you do so by modeling the needs of the business and the needs of the application independently. This means that you are not creating a single system, but one or more systems (your application or applications) that are utilizing a consummate subsystem (your domain).
Personally, I do not have the three types of data-bearing classes that you describe in any of my projects. Instead, I have only my domain model and a view model representation based on each distinct UI requirement. I have found that the need to have a separate set of persistence classes to be superfluous. There are several ways to eliminate the need for persistence classes, such as POCOs with code-first EF, object databases/NoSQL, and separation of your read model and write model. I opt for a combination of the last two, personally, in most cases.
The translation layer between the domain and application/UI is something that I find to be required, because the "truth" that the domain represents is infallible. But, in order to attain a usable interface into the domain, the application will sometimes have additional or differing requirements to the domain. That means that this translation layer is not just about field mapping, it is about encapsulation of differing concepts and isolation of usage scenarios.
Since the domain should have absolutely no knowledge of how it is used, that means that there is a requirement for translation and it is not something that should be attempted to be worked out of the system. I have seen people who have used their domain classes directly in the UI, as the actual model, and that is more heinous (in my opinion) than having to create a translation layer. You are looking at it from the perspective of just being for translation, but remember that it is also about isolation. Introduction of new concepts, changing of existing concepts, and other changes within the domain can effectively be intercepted in translation to prevent impact in the UI, and vice versa.
That sounds trivial, but in an enterprise setting, it is not uncommon for there to not be just a single application that utilizes the domain, but multiple applications. Consider the possibility that your domain is serving a desktop application, a web application, and a REST API. Each of those will have their own specific application requirements that are separate from your business requirements. They also will likely want to represent the domain differently from each other. This means that each of them will likely have things such as different validation requirements, different views into your domain, and unique application functionality. Regardless of all of this, the domain remains happily oblivious to it all. You will have to translate differently for each, somewhere above the domain.
If you are finding that your models are looking exactly like your domain, with a majority of it being one-to-one mappings, you might want to take a step back and look for some other issues that might be occurring. I find a large number of two-way mappings of singular fields to be a code smell. Not always, but often, this is an early sign of an anemic domain model. I personally go as far as to enforce architectural requirements on my domain model, such as requiring that properties be read-only (forcing them to be set through a constructor for existing data and changed through methods on the classes), etc. It is fairly trivial to write architectural unit tests which will reflect your domain classes to inspect them for possible violations of such rules. But, the point is if you find translation to be your pain point, make sure that your domain model is not just acting as a data container. Anemic domain models are an extraordinarily common pitfall in DDD implementations, and with an anemic domain model, there is actually very little benefit to a DDD approach at all, as you are taking the power and responsibility away from the place it should be enforced.
Business requirements should be reflective of the needs of the domain, which is not the same thing as the usage patterns of the domain. Ideally, you should be telling the domain how you want to change its state, and the domain should be applying the domain logic to allow or disallow those changes. If you find yourself pulling down a full domain model representation for a part of the domain, translating the entire thing to a model or DTO, modifying that model or DTO, translating it back to the domain representation, and sending the whole thing back in, you likely have a larger problem.
You may want to review your understanding of DRY. A good starting point is DRY is about Knowledge -- Matthias Verraes (2014).
You may also want to look at Gary Bernhardt's 2012 talk Boundaries.
The key idea is this - the DTO model is an API contract between the domain model and the presentation components. It gives us the freedom to aggressively update/adapt/improve the domain model without breaking the existing presentation component.
Similarly, the data access model is an API contract between the domain and the presentation component. Not only does this mean that the interface between the domain and persistence is stable, but it also provides a stable contract between the current implementation of the domain model (which writes data today) and future implementations of the domain model (which read back that same data tomorrow).
1. This is not about Domain-Driven Design
Separating models comes with your ancestral n-layer architectural style. It dates back long before DDD was around.
2. You don't have to have that many models
If your application is simple enough, you can ditch some of them.
"Data access model" comes to mind first. It's only a recent addition to the DDD paraphernalia. But you can do without just as well, with a minor impact on your domain model.
And guess what, you may even find out that you don't need a rich domain model at all... Some applications are just better off as CRUD.
If you find something "irritable", get rid of it and see for yourself what the benefits/drawbacks are. Code police won't come knocking at your workplace and lock you up for favoring simplicity over so-called orthodoxy.
No, there are not many models. There are multiple representations of the same model. This distinction is very important.
In the domain model, the entity is responsible of making sure that it's state is instact. For instance, the ApprovedAt property may not be set unless ApprovedBy is set at the same time. This is usually done by adding behavior to the entity. I do it by always setting all property setters to private and then add methods every time the entity need to change state.
The DTO is responsible of transferring state between over application boundaries. But when you do DDD correctly you do not want to transfer the domain entity to the client. You want it to remain safe within the server. Thus the role of the DTO is much more important. You might even have multiple DTOs for the same entity. For instance, I might have a UserListDTO which contains a subset for just listing entities and maybe a UserDetailsDTO which is designed for the user details page. For writes you just transfer the mutated state or send command influenced DTOs (ApproveUserDTO).
Finally it's important that the domain entity isn't forced to be designed in a certain way just to be able to persist it. That's why we have the data entity. It will be design so that everything can be persisted in a efficient way. The user might have a data entity called User and one called UserField depending on the domain entity design.
The conclusion is that if you models look exactly the same you are doing something wrong (from the perspective of DDD).

Pulling out business logic from the data access layer

We are writing some support applications (rather small) to our ERP system.
Thus until now I am feeling that I am using the Data Access Layer for 2 roles: the business layer AND the data access one.
I am having trouble deciding what I have to move to a separate layer and if I need to. I have read somewhere that knowing when to make layer separation is wisdom and knowing the patterns is just knowledge. I have neither in adequate amounts.
So I need some help to determine what is what.
My current DAL deals with fetching the data and applying basic logic on them. For example there are methods like
GetProductAvailabilitybyItem
GetProductAvailabilitybyLot
etc.
If I needed to separate them what I would have to do?
One other matter that is in my head is that in order to normalize my DAL and make it return different entities every time (through one general get method) I would have to use DataTable as return type. Currently I am using things like List<PalletRecord> as return types.
I feel that my apps are so small that its hard (and maybe useless) to discriminate these 2 layers.
My basic need is to build something that can be consumed by multiple front-ends (web pages, WinForms, WPF, and so on).
Additional Example:
Lets talk some barcode. I need to check if a fetched lot record is valid or not. I am fetching the record in DAL and produce a method returning bool in business layer?
Then i can call the bool method from whatever presentation in order to check if a textbox contains a valid lot?
Is this the logic extremely simplified?
Based on your description, you should definitely separate both layers right now, when the application is still small. You might feel a BL is useless when you're just accessing and displaying data, but with time you'll find the need to modify, transform, or manipulate the data, like coordinate object creation from different tables, or update different tables in a single action from the user.
The example you provided helps to support this idea, although is quite simplified.
Pablo's answer does offer some good design ideas too: you should definitely use an ORM to simplify your DAL and keep it very thin. I've found NHibernate and Fluent make a very good job on this. You can use the BL to coordinate access using Data Access Objects.
Given that you are dealing with very small applications, why not just have an ORM provide all data-access for you and just worry about the business layer?
That way you don't have to worry about dealing with DataTable's, mapping data to objects and all that. Much faster development, and you would reduce the size of the codebase.
For example, NHibernate or Microsoft's Entity Framework
Now, if you will be providing data to external consumers (you are implementing a service), you may want to create a separate set of DTOs that go through the wire, instead of trying to send your actual model entities.
I am not a big fan of nTire architecture and have some good reasons for it.
Main objective for such an architecture are
Ability to work with different underlying database separation of
context - i.e. application design and business logic Uniformity and
confirmation of best patterns and practices.
However, while doing so, you also make some sacrifices such as give up provider specific optimizations etc.
My advise is, you can go with two layer architecture,i.e. Data access and business logic layer and GUI or presentation layer. It will still allow you to have a common code for different platforms and at the same time will save you from spaghetti code.

Enterprise Design Pattern Question

Something on my mind about structuring a system at a high level.
Let's say you have a system with the following layers:
UI
Service Layer
Domain Model
Data Access
The service layer is used to populate a graph of objects in the domain model. In an attempt to avoid coupling, the domain model will be not be persistence aware and will not have any dependencies on any data access layer.
However, using this approach how would one object in the domain model be able to call other objects without being able to load them with persistence, thus coupling everything together - which I'd be trying to avoid.
e.g. an Order Object would need to check an Inventory object and would obviously need to tell the Inventory object to load in some way, or populate it somehow.
Any thoughts?
You could inject any dependencies from the service layer, including populated object graphs.
I would also add that a repository can be a dependency - if you have declared an interface for the repository, you can code to it without adding any coupling.
One way of doing this is to have a mapping layer between the Data Layer and the domain model.
Have a look at the mapping, repository and facade patterns.
The basic idea is that on one side you have data access objects and on the other you have domain objects.
To decouple you have to: "Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)
Here are some links on the subject:
Gamma interview on patterns
Random blog article
Googling for "Program to an interface, not an implementation" will yield many useful resources.
Have the domain model layer define interfaces for the methods you'll need to call, and POCOs for the objects that need to be returned by those methods. The data layer can then implement those interfaces by pulling data out of your data store and mapping it into the domain model POCOs.
Any domain-level class that requires a particular data-access service can just depend on the interface via constructor arguments. Then you can leverage a dependency-injection framework to build the dependency graph and provide the correct implementations of your interfaces wherever they are required.
Before writing tons of code in order to separate everything you might want to ask yourself a few questions:
Is the Domain Model truly separate from the DAL? And yes, I'm serious and you should think about this because it is exceedingly rare for an RDBMS to actually be swapped out in favor of a different one for an existing project. Quite frankly it is much more common for the language the app was written in to be replaced than the database itself.
What exactly is this separation buying you? And, just as important, what are you losing? Separation of Concerns (SoC) is a nice term that is thrown about quite a bit. However, most people rarely understand why they are Concerned with the Separation to begin with.
I bring these up because more often than not applications can benefit from a tighter coupling to the underlying data model. Never mind that most ORM's almost enforce a tight coupling due to the nature of code generation. I've seen lot's of supposedly SoC projects come to a crash during testing because someone added a field to a table and the DAL wasn't regenerated... This kind of defeats the purpose, IMHO...
Another factor is where should the business logic live? No doubt there are strong arguments in favor of putting large swaths of BL in the actual database itself. At the same time there are cases where the BL needs to live in or very near your domain classes. With BL spread in such a way, can you truly separate these two items anyway? Even those who hate the idea of putting BL in a database will fall back on using identity keys and letting the DB enforce referential integrity, which is also business logic..
Without knowing more, I would suggest you consider flattening the Data Access and Domain Model layers. You could move to a "provider" or "factory" type architecture in which the service layer itself doesn't care about the underlying access, but the factory handles it all. Just some radical food for thought.
You should take a look at Martin Fowler's Repository and UnitOfWork patterns to use interfaces in your system
Until now I have seen that application can be well layered into three layers: Presentation-->Logic-->Data--and Entities (or Bussines Object). In the Logic Layer case you can use some pattern such as Transaction Script or Domain Model I'm supposing you're using this last. The domain model can use a Data Mapper for interacting with the data layer and create business objects, but you can also use a Table Module pattern.
All this patterns are described in Marttin's Fowler Patterns of Enterprise Application Architecture book. Personally I use Transaction Script because it is simplest than Domanin Model.
One solution is to make your Data Access layer subclass your domain entities (using Castle DynamicProxy, for example) and inject itself into the derived instances that it returns.
That way, your domain entity classes remain persistence-ignorant while the instances your applications use can still hit databases to lazy-load secondary data.
Having said that, this approach typically requires you to make a few concessions to your ORM's architecture, like marking certain methods virtual, adding otherwise unnecessary default constructors, etc..
Moreover, it's often unnecessary - especially for line-of-business applications that don't have onerous performance requirements, you can consider eagerly loading all the relevant data: just bring the inventory items up with the order.
I felt this was different enough from my previous answer, so here's a new one.
Another approach is to leverage the concept of Inversion of Control (IoC). Build an Interface that your Data Access layer implements. Each of the DAL methods should take a list of parameters and return a Data Table.
The service layer would instantiate the DAL through the interface and pass that reference to your Domain Model. The domain model would then make it's own calls into the DAL, using the interface methods, and decide when it needs to load child objects or whatever.
Something like:
interface IDBModel {
DataTable LoadUser(Int32 userId);
}
class MyDbModel : IDBModel {
DataTable LoadUser(Int32 userId) {
// make the appropriate DB calls here, return a data table
}
}
class User {
public User(IDBModel dbModel, Int32 userId) {
DataTable data = dbModel.LoadUser(userId);
// assign properties.. load any additional data as necessary
}
// You can do cool things like call User.Save()
// and have the object validate and save itself to the passed in
// datamodel. Makes for simpler coding.
}
class MyServiceLayer {
public User GetUser(Int32 userId) {
IDBModel model = new MyDbModel();
return new User(model, userId);
}
}
With this mechanism, you can actually swap out your db models on demand. For example, if you decide to support multiple databases then you can have code that is specific to a particular database vendors way of doing things and just have the service layer pick which one to use.
The domain objects themselves are responsible for loading their own data and you can keep any necessary business logic within the domain model. Another point is that the Domain Model doesn't have a direct dependency on the data layer, which preserves your mocking ability for independent testing of business logic.
Further, the DAL has no knowledge of the domain objects, so you can swap those out as necessary or even just test the DAL independently.

Generic business layer design with repository pattern with c# (how)

I am using a repository design with web applications (repository (data layer) exposing model (objects) to the business layer which is then consumed to the data layer (ui). Objects or lists of objects are passed between the layers with this type of implementation.
I am finding my business layer is a becoming a series of manager type classes which all have common GetAll, GetById, Save, Delete type methods. This is very common with a number of very small simple objects. This is the area of concern or opportunity for improvement (the series of smaller business manager classes). I am looking for options to avoid the whole series of smaller business manager classes mapping to the smaller objects which only do get/save/delete object.
The bigger objects which are closer to the functionality to the application have a number of methods in addition to the get/save/delete type methods (these manager classes are ok).
I am thinking there is a design pattern or implementation which will allow me to have one manager class which resides in the business layer which would accept an object as a parameter of a particular object type and the get/save/delete methods respectively know the type of repository object to spin up and pass the object to it for its operation.
The benefit here would be that I can have one generic manager class to pass save/delete/get's for smaller type objects to the appropriate repository class thereby reducing the many smaller manager classes.
Ideas on how to accomplish this?
thx
I would not go that way. The business layer classes can be as simple as code that forwards to the data layer, and it is true that they can be annoying to write, but they exist for a couple of reasons: validation, security, taking some actions based on business rules.
If you try to make a generic business layer, it will hard to include all the various things that a business class could do. The generic business layer will become much more complex than the one you currently have. Testing will be much harder. Adding a new business rule will be hard, too.
Sorry, this is not what you wanted to read, but I have already gone the route of generic systems and have always had lots of regrets.
The idea behind a repository (or a dao), is to further abstract data access concerns away from the business layer in order to simplify that layers focus on the "business" of a given domain.
That said, there are many common plumbing type of concerns that are reuseable across different applications, some of which do lend themselves to a supertype in the business layer. Consider the cross cutting concern of being able to retrieve a given business entity by some Id from a database, and you might come to the conclusion that it is in fact useful to have an Id property in a business layer supertype. It might even be useful if entities considered that Id when determining equality. Etc..
Now I do believe that Timores is right in principal and trying to write one application that fits all domains is both incredibly painful and totally fruitless, but I also beleive the the art of the profession is knowing how to use a variety of tools and when to apply which one, and having some core infrastructure code should be in your tool belt.
For a good idea of a framework concept for a web app that has been road tested, take a look at SharpArch.
HTH,
Berryl

Best practice to apply domain driven design in .NET?

I have been trying to learn and apply domain driven concept into my software development. The first thing that I try to do is creating my domain model based on business logic needs. I often also use OR Mapping tool, such as LLBLGen, NHibernate, or Linq to SQL, to create data model and data access layer. The domain model and data model, however, are often very similar which make me wonder what benefit I really get by maintaining two models.
Can someone share their practical thoughts about domain driven design? Furthermore, how would you deal with data model or data access layer when applying DDD in your application?
Thanks in advance.
EDIT
Found a good article, with sample code, about Repository Pattern.
I abstract my data access via the Repository pattern, so keep my domain objects completely POCO and data provider agnostic.
This allows me to sculpt my application from a domain perspective, concentrating on the logic, primarily via Unit Tests.
Once this has settled I put in the Presentation layer (usually web pages) and then commit to the concrete database schema. I then implement my concrete Repository classes, which can be L2S.
I've drafted a couple of articles here - http://www.duncangunn.me.uk/dasblog/2009/04/11/TheRepositoryPattern.aspx
http://www.duncangunn.me.uk/dasblog/2009/06/27/MockingLinqToSQLRepositories.aspx
Keep an eye out over the next couple of weeks as I will be documenting and providing sample code of my implementation which uses Unit of Work pattern also.
We map domain objects directly to the database, means that we do not have separate layer for data access, and rather we treat this as infrastructure code.
We use Fluent NHibernate for most of the configuration.
Splitting bounded contexts is also a big DDD benefit, you resolve each problem in its context, even if you must duplicate data between contexts.
Good aggregate roots definition gives a simpler design and leads to potential performance improvement (scalability through grid computing, see Gojko Adzic post).
When your design becomes really Domain Driven, your applications is more supple to new business needs, because implementation becomes really an implementation detail.

Categories