I've got two entities in the entity framework. Now I want to seperate them by putting an Interface of the DAL entity into the Domain.
So the end result would be:
DAL
Person : IPerson (EF Entity)
Book : IBook (EF Entity)
Domain
Interfaces (Folder)
IPerson
IBook
Person (Domain entity)
Book (Domain entity)
Now the problem is, should my Dal.Person have a virtual Book or IBook?
How should both the DAL.Person, IPerson and Domain.Person look like (give me just really small example for the interfacing)
EF doesn't support working with interfaces so you cannot have public virtual IBook ... in your Person entity if you want to use it as navigation property handled by EF.
The answer to your question entirely depends on your objective here.
If you are creating domain level Interfaces with the rationale that you might (at some stage later) swap over the DAL from Entity Framework to something entirely different (such as a 3rd party web-service, or perhaps xml serialisation) - then you will be aiming to completely seperate any concrete logic between the Domain and the DAL.
Where possible, you want your Domain to operate on the Domain entites/interfaces and your DAL to operate on DAL entities/interfaces, whilst implementing the interfaces specified in your Data Access
Therefore, your DAL object DAL.Person should contain a Book object, and implement from the IPerson interface at a domain level.
I'll give some examples as requested:
#region Domain Objects
public interface IPerson
{
List<IBook> Books { get; private set; }
}
public interface IBook
{
string Name { get; private set; }
}
#endregion
#region DAL/Entity Framework Auto Generated classes
public class Person : IPerson
{
public List<Book> Books {get; private set;}
}
public class Book : IBook
{
public string Name { get; private set; }
}
#endregion
Contrary to Jodrells comment, I think that if there was a requirement to 'Hot-Swap' the Data Access Layer there could be a case for the DataAccess layer implementing the interface contracts described in the Domain layer.
To be honest though, it is rare that I have seen this requirement - and usually you are best off extending the auto-generated Entity Framework classes (through partial) and passing around the application, removing the duplication that would be required by specifying the domain objects and contracts themselves.
So in essence, your Entity-Framework classes becomes your Domain layer.
And I should mention that you should use POCO classes as per comments above
I've not seen Interfaces used to decouple EF. I know they are used for decoupling with dependency injection, but perhaps there is too much going on with EF behind the scenes for this to work (dynamic proxies, change detection).
I'd suggest implementing a Repository layer.
Step 1
Start with the simplest pattern - model (Person and Book) in a domain and EF in a DAL layer, using the standard EF procedure for code first. EF implements repository features in the DbSet<Person> and DbSet<Book> (but of course this type of repository is locked into EF).
Make a deliverable app work with this pattern, you can demo functionality quite quickly. This allows you to focus on app logic and not worry too much about persistence.
Step 2
Put a repository class or classes between domain and DAL. Replace the domain calls to DbSet<Person> and DbSet<Book> with calls to IQueryable<Person> and IQueryable<Book> in the repository. The repository collections initially just point at the EF DbSet<> collections.
Implement Save() in the repository as well. Initially, it just calls DbContext.SaveChanges().
Check the functionality stays the same.
Step 3
Replace the source of the repository IQueryable<>'s with whatever is equivalent in your new DAL. This may or may not be tricky, depending on the shape of the new DAL.
I followed this kind of process - started with an XML serialized DAL, moved it to EF, refactored one table back to a local XML file, and next step will be to refactor another table to a web service on an ESB.
BTW, you mention replacing EF with SQL for performance. We found EF slow for bulk inserts, because of the row-by-row style it uses.
To get around this, I implemented SqlBulkCopy within the EF based repository (instead of wholesale replacement of EF which has other features we really liked). It's quick, but takes a while to piece together.
I've been having this problem for AGES.
In the past I have used DTOs with AutoMapper, but this never seemed very elegant, but I think I've found a slightly neater way - have a look and see if it suites your design.
Basically you expose TWO links in your - in your concrete class - one implemetents the Ibook Book and one that implements Book BookNavigation
the first one implements the interface requirements (Ibook) and the second implements a concrete class to make EF Happy. You then bind the two to the SAME underlying private Book book.
I explain it in more detail here:
http://bretthargreaves.wordpress.com/2014/11/11/entity-framework-and-interface-issues/
Related
My goal is async loading of related entities using DBContext.
Let imagine two projects. The first named MyApp.Domain and contains domain entities.
namespace MyApp.Domain
{
public class PlanPage
{
public Guid Id { get; set; }
}
}
namespace MyApp.Domain
{
public class PlanPageDay
{
public Guid Id { get; set; }
public Guid PlanPageId { get; set; }
}
}
The second project named MyApp.Infrastructure.EntityFramework and contains configuration of projection entities to database. It also contains class which extends domain entity and implements Entity framework specific logic.
namespace MyApp.Infrastructure.EntityFramework.Models
{
public class PlanPageEntity : PlanPage
{
private readonly ApplicationDbContext _applicationDbContext;
protected PlanPageEntity(ApplicationDbContext applicationDbContext)
{
_applicationDbContext = applicationDbContext;
}
public ICollection<PlanPageDay>? Days { get; set; }
public async Task<ICollection<PlanPageDay>> GetDays()
{
return Days ??= await _applicationDbContext.PlanPageDays
.Where(pd => pd.PlanPageId == Id)
.ToListAsync();
}
}
}
The purpose of this example is simple. We separate infrastructure code from domain code. Look how do we plan to use this concept:
// Entity initializing code. Placing somewhere in domain logic.
var plan = new PlanPage(/*some constructor arguments*/);
// Entity loading code. Placing somewhere in infrastructure implementation.
public async Task<PlanPage> GetPlanPage(Guid id)
{
return await _applicationDbContext.Set<PlanPageEntity>().FindAsync(id);
}
Note that we tell to Entity framework to use child class (PlanPageEntity) so it can handle all specific things that it can.
The question is: Is it possible to configure the EF so that it allows us to use this concept?
As requested here's a little more details for my opinion stated in the comments.
The main reason why I think your current approach is a bad idea is that it violates the separation of concerns design principle: when you are mixing domain models with data access models, you make your domain logic completely dependent on how you model the data in your database. This quickly limits your options because the database may have some restrictions on how you can model your data that doesn't fit well with the domain logic you want to implement as well as making maintenance difficult. E.g. if you decide to split up one DB table into two then you might have a big task ahead of you in order to make your domain logic work with those two new models/tables. Additionally, making performance optimizations in your database easily becomes a nightmare if not thought through ahead of time - and you shouldn't spend time thinking of optimizing your system before it's necessary.
I know this is a little abstract since I don't know much about your domain but I'm sure I could find more arguments against it.
Instead, separating data access models (and in general all external data models) from your domain models makes it much easier to maintain: if you need to make some changes to your database, you simply need to update the logic that maps the data from your data access models to your domain model - nothing in your domain logic needs to change.
In the examples you have given, you have already logically separated your domain models and data access models into two separate projects. So why not follow through with that thought and separate the two with a binding/mapping layer in-between?
Is it possible to configure the EF so that it allows us to use this concept?
Yes. Essentially you have DTO's, and your Entities derive from your DTOs. So when you fetch an Entity you can return it directly. But if you wouldn't be able to attach a non-Entity, so you'd have to map it. It's going to be inconvenient, and like 99.999% of bespoke entity and repository designs, will be ultimately a waste of time.
This is somewhat similar to the what EF already does for you. Start with persistence-ignorant Entity classes, and introduce persistence-aware runtime subtypes for scenarios that require them, which is basically just Lazy Loading.
i am trying to get control over DDD with EF code first. i saw when people work with EF code first then domain classes reside there in same classes. just see a small example.
public class TestDBContext : DbContext
{
public TestDBContext()
: base("name=TestDBContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Configurations.Add(new vwCustomerConfiguration());
Database.SetInitializer<TestDBContext>(null);
}
public DbSet<Customer> Customer { get; set; }
public DbSet<Addresses> Addresses { get; set; }
public DbSet<Contacts> Contacts { get; set; }
public virtual DbSet<vwCustomer> vwCustomers { get; set; }
public DbSet<vwMyCustomers> vwMyCustomers { get; set; }
}
customer, address, contact and all domain classes are in same project but i want to put all these domain classes in different project.
just see new project hierarchy which i am thinking to implement. all project name will start with my company then do and project name
here it is
1) Impex.Domain
2) Impex.Storage
3) Impex.Business
4) Impex.UI
so i will have 4 layers and those are domain, Storage, Business and UI. Storage, Business and UI these 3 layer will have reference of Domain layer because these 3 layers Storage, Business and UI may use domain classes.
UI will pass data to business layer and received data from business layer. business layer again will talk to Storage layer where EF code first will be implemented to interact with DB.
if i can successfully complete my project following 4 layers then people should consider my project is based on DDD pattern or not ?
so tell me am i thinking right way. please tell me all your suggestion and guidance. if anyone can foresee any problem then also please aware me in details. thanks
Your question seems largely around the structure of your solution, as with most things in our industry once you understand the principles of a thing (DDD in this case) the structure seems to sort it self out.
I would point out a couple of things to help you along your way
1) Impex.Domain
Keep your entities clean don't reference EF from this project
Capture your business logic in your entities & aggregates rather than in a 'business' layer, your entities should be responding to events and actions rather than having a 'layer' that tells it what to
As a poor example, do something like
employee.takeLeave(days)
Instead of
employee.daysOff = days;
i.e. Modifying the state of the entity should be captured internally to the entity.
2) Impex.Storage
Since you are using EF (and not going to pollute your Domain models with EF related attributes) you will have to use the Fluent Api to configure your EF model (see msdn, ef tuts, and SO to get some ideas) in particular, primary keys and indexes will need to be configured here.
Something like
modelBuilder.Entity<Employee>().HasKey(t => t.EmployeeID);
Other than that nothing exiting here use standard repository patters etc.
3) Impex.Business & Impex.UI
As mentioned in point 1 it doesn't make sense to have a business layer, rather what this layer would be is an Application or Service layer, here you would load the entity or aggregate and invoke the work to be completed.
Also a responsibility of the layer would be to map between ViewModels &/OR Request & Response POCOs (sent to and from your UI/Api), you would not expose your Domain Models outside of the Domain boundary see hexagonal architecture
Last note:
DDD does not dictate the architecture! It's a set of principles to guide you, but you can implement as a 1 tier, 3 tier, CQRS or anyother architectural pattern you like as long as you adhere to the tenants of DDD.
Good luck.
I am trying to grabs the idea of the pattern repository and trying to get it implemented in database structures I've already set up in the past. I'm now trying to get the best practice to work with my lookup tables. I've created a test project to play around and this is my database model:
You can see that I have three tables for the lookups: Lookup, Language and LookupLanguage. Language table simply contains the languages.
Lookup tables holds the different types used throughout the models.
And LookupLanguage links the both tables together:
I've created anew project with all the models 1 to 1 to the database tables:
I also created a generic repository and a generic CrudService interface:
public interface ICrudService<T> where T : IsActiveEntity, new()
{
int Create(T item);
void Save();
void Delete(int id);
T Get(int id);
IEnumerable<T> GetAll();
IEnumerable<T> Where(Expression<Func<T, bool>> func, bool showDeleted = false);
void Restore(int id);
}
Now, according to the following post: When implementing the repository pattern should lookup value / tables get their own Repository? , the repository should hide the underlying database layer. So I think I need a new implementation of a service and/or repository to get the lookups, but then, where do I have to tell in which language I need to have the lookup?
Let's take the status (new, accepted, refused) from the company as an example.
The company model is as follow:
public partial class Company : IsActiveEntity
{
[Required]
[MaxLength(50)]
public string CompanyName { get; set; }
public System.Guid StatusGuid { get; set; }
[ForeignKey("StatusGuid")]
public virtual Lookup Status { get; set; }
}
I guess I don't need to have a separate implementation of a repository?
But I need a separate implementation CompanyService.
interface ICompanyService : ICrudService<Company>
{
IQueryable<LookupLanguage> GetStatuses(Guid languageguid);
LookupLanguage GetStatus(Guid statusguid, Guid languageguid);
}
Is this the correct approach, or do I miss something here?
Creating a Generic LookupRepository in your case in a better option because of your table schema and maintainence perspective.
I'm not sure whether you are using both Service Locator and Repository pattern or just Repository because of the name ICompanyService. But regardless, I agree that Repositories should not represent tables 1-1 always but they do most of the times.
The SO link you provided has a different table structure than yours. You have a generic lookup table vs the link has a separate table for each lookup. In the case where you have separate tables it makes sense to have the lookup repository method go with the entity repository since you will have a separate code to fetch the data for each lookup(as they have separate tables with different schema).
But in you case you have a single table that stores all the lookup types for each language and it makes sense to have a single LookupRepository that returns all the various types of lookups based on Language and LookupType. If you create each lookup method in separate entity repositories (like GetStatuses in CompanyRepository and GetStatuses in ContactRepository) you will have to repeat the logic in the method for each repository.
Think if you change the schema of the lookup table (say add a column) and you want to test all places the lookups are used it will be nightmare if you have lookup methods all over the place and pretty easy if you have one method in LookupRepository.
interface ILookupService : ICrudService<Lookup>
{
IQueryable<Lookup> GetStatuses(Guid languageguid, LookupType lookupType);
Lookup GetStatus(Guid statusguid, Guid languageguid, LookupType lookupType);
}
As regards your question, "Is this the correct approach" - this entirely depends on your specific needs.
What you have done doesn't seem to have any real issues. You have implemented the repository pattern using generics which is great. You are using interfaces for your repositories which allows for easier unit testing, also great!
One of your tags seems to indicate you are interested in the Entity Framework. You do not seem to be using that. The Entity Framework would simplify your code by creating the boiler plate classes for you. You can still use your repository pattern code with the classes created by the Entity Framework.
It seems that you are confusing the idea of a service and a repository. A repository is a general object which allows you to get data from a store without caring about the implementation. In your example, ICompanyService is a repository.
It is really controversial topic and there are different approaches to this problem. In our data logic we are not using repository pattern because we do not want to abstract most of the benefits of Entity Framework. Instead, we pass the context to the business logic which is already a combination of UoW / Repository pattern. Your approach is okay if you are going this way on all of your company services. However what I have seen so far, putting methods to the related services by their return values is the best approach to remind where they are. For instance if you want to get the company lookup, create a ILookupService and put GetLookUpsByCompany(int companyId) method to retrieve the company lookups.
I would argue with the linked response. Repositories ARE linked to database entities, considering the Entity Framework itself as a uow/repository implementation is a best example. On the other hand, services are for domain concerns and if there is a mismatch between your database entities and domain entities (you have two separate layers), services can help to glue the two.
In your specific case, you have repositories although you call them services. And you need a repository per database entity, that's just easier to implement and maintain. And also it helps to answer your question: yes, you need the extra repository for the linking table.
A small suggestion. You seem to have a generic query function that only accepts where clauses
IEnumerable<T> Where(Expression<Func<T, bool>> func, bool showDeleted = false);
If you already follow this route that allows arbitrary filtering expressions (which itself is a little arguable as someone will point out that you can' possibly guarantee that all technically possible filters can be executed by the database engine), why don't you allow all possible queries, including ordering, paging, etc:
IQueryable<T> Query { get; }
This is as easy to implement as your version (you just expose the dbset) but allows clients to perform more complicated queries, with the same possible concern that such contract is possibly too broad.
Localization is a presentation layer thing. The lower layers of your application should bother with it as little as possible.
I see two different kind of lookups: translations of coded concepts (Mr/Miss/Mrs) and translations of entity properties (company name maybe, or job titles or product names).
Coded concepts
I would not use lookup tables for coded concepts. There is no need to bother the lower layers at all with this. You will only need to translate them once for the entire application and create simple resource files that contain the translations.
But if you do wish to keep the translations in the database, a separate lookup repository for the codes or even per code system will sort of replace the resource file and serve you fine.
Entity properties
I can imagine different/nastier localization issues when certain entities have one or more properties that get translated in different languages. Then, the translation becomes part of the entity. I'd want the repository to cough up entity objects that contain all translations of the description, in a dictionary or so. Cause the business layer should not worry about language when querying, caching and updating relations. It should not ask the company repository for the Dutch version of company X. It should simply ask for company X and be served a Company object that contains its name in Dutch, English and French.
I've one more remark about the actual database implementation:
I think the lookup tables are distracting from the actual entities, to the point where you have forgotten to create a relation between person and person company. ;) I'd suggest putting all translations of entity properties in a single XML type column instead.
This illustrates why the repository should handle entities plus translations. If you were to make this storage layer level implementation change at some point, i.e. go from lookup tables to xml columns, the repository interfaces should remain the same.
I am learning DDD development for few days, and i start to like it.
I (think i) understand the principle of DDD, where your main focus is on business objects, where you have aggregates, aggregates roots, repositories just for aggregates roots and so on.
I am trying to create a simple project where i combine DDD development with Code First approach.
My questions are: (I am using asp.net MVC)
DDD Business Objects will be different than Code First objects?
Even if they will probably be the same, for example i can have a Product business object which has all the rules and methods, and i can have a Product code first (POCO) object which will just contain the properties i need to save in database.
If answer to question 1 is "true", then how do i notify the Product POCO object that a property from business object Product has been changed and i have to update it? I am using an "AutoMapper" or something like this?
If the answer is "no", i am completely lost.
Can you show me the most simple (CRUD) example of how can i put those two together?
Thank you
Update I no longer advocate for the use of "domain objects" and instead advocate a use of a messaging-based domain model. See here for an example.
The answer to #1 is it depends. In any enterprise application, you're going to find 2 major categories of stuff in the domain:
Straight CRUD
There's no need for a domain object here because the next state of the object doesn't depend on the previous state of the object. It's all data and no behavior. In this case, it's ok to use the same class (i.e. an EF POCO) everywhere: editing, persisting, displaying.
An example of this is saving a billing address on an order:
public class BillingAddress {
public Guid OrderId;
public string StreetLine1;
// etc.
}
On the other hand, we have...
State Machines
You need to have separate objects for domain behavior and state persistence (and a repository to do the work). The public interface on the domain object should almost always be all void methods and no public getters. An example of this would be order status:
public class Order { // this is the domain object
private Guid _id;
private Status _status;
// note the behavior here - we throw an exception if it's not a valid state transition
public void Cancel() {
if (_status == Status.Shipped)
throw new InvalidOperationException("Can't cancel order after shipping.")
_status = Status.Cancelled;
}
// etc...
}
public class Data.Order { // this is the persistence (EF) class
public Guid Id;
public Status Status;
}
public interface IOrderRepository {
// The implementation of this will:
// 1. Load the EF class if it exists or new it up with the ID if it doesn't
// 2. Map the domain class to the EF class
// 3. Save the EF class to the DbContext.
void Save(Order order);
}
The answer to #2 is that the DbContext will automatically track changes to EF classes.
The answer is No. One of the best things about EF code-first is that it fits nicely with DDD since you have to create your business objects by hand so do use your EF models to be equivalent to DDD entities and value objects. No need to add an extra layer of complexity, I don't think DDD recommends that anywhere.
You could even have your entities to implement an IEntity and you value objects to implement IValue, additionally follow the rest of DDD patterns namely Repositories to do the actual communication to the database. More of these ideas you can find this very good sample application in .NET, even though it doesn't use EF code first, it's still very valuable: http://code.google.com/p/ndddsample/
Recently I've done similar project. I was following this tutorial: link
And I've done it this way: I've created Blank solution, added projects: Domain, Service and WebUI.
Simply said in domain I've put model (for example classes for EF code first, methods etc.)
Service was used for domain to communicate with world (WebUI, MobileUI, other sites etc.) using asp.net webapi
WebUi was actually MVC application (but model was in domain so it was mostly VC)
Hope I've helped
The Pluralsight course: Entity Framework in the Enterprise goes into this exact scenario of Domain Driven Design incorporated with EF Code First.
For number 1, I believe you can do it either way. It's just a matter of style.
For number 2, the instructor in the video goes through a couple ways to account for this. One way is to have a "State" property on every class that is set on the client-side when modifying a value. The DbContext then knows what changes to persist.
Late question on this topic.
Reading Josh Kodroff's answer confirms my thoughts about the implementation of a Repository to, for instance, Entity Framework DAL.
You map the domain object to an EF persistance object and let EF handle it when saving.
When retrieving, you let EF fetch from database and map it to your domain object(aggregate root) and adds it to your collection.
Is this the correct strategy for repository implementation?
Say I've got a domain model created from C# classes like this:
public class MyClass
{
public string MyProperty { get; set; }
}
Along with the model, I have defined repository interfaces classes for IoC.
Now, I'm trying to turn this POCO domain model into a set of Entity classes using LINQ mapping. (This approch was recommended in a book I'm reading on MVC.) In the example above this was easy enough to do with a few attributes without impacting the 'plain oldness' of the classes:
[Table]
public class MyClass
{
[Column]
public string MyProperty { get; set; }
}
The problem comes when I start to map associations, change modifications and such. It seems that I'm quickly destroying the original concept of the domain model, and instead simply creating a set of LINQ-to-SQL classes. Am I missing something? Are these classes still the correct place for business logic? Will I still be able to and should I continue to load data into these classes from non-LINQ, non-DB sources?
Thanks
This post, also on SO, answers my question: (Thanks Google)
Entity classes decoupled from LINQ to SQL provider for implementing the Repository pattern. How?
EDIT:
Well maybe not, is this a common complaint about entity classes?
ANOTHER EDIT:
Ok, so basically this cannot be done at the moment, but with .NET 4.0 it is supposed to be possible.
There have been several other question like this.
I played with EF4 this week end, you can follow Julie Lerman blog post serie to implement a Repository pattern with EF4. It works well, although it's no yet completely straight forward...
As far as I know there is no way to do this with EF3.5. Good luck.