Query against Domain Classes should resolve against Entities - entity-framework

I am trying to build a generic repository that allows querying against domain classes.
My Repository interface looks like the following:
public interface IRepository<T>
{
T Get(int id);
IQueryable<T> Query();
void Add(T model);
void Remove(T model);
}
Given I have an UserEntity entity framework class and a User domain class, I want to query against the User. The UserEntity should not be exposed to other services, because it should be internal to the Entity Framework layer.
A query like userRepository.Query().Single(user => user.UserName == "Toni") should return a User domain class. However internally it should query against an IDbSet<UserEntity> returned from my entity framework. The Expression Tree (which contains the Single query operation) should be attached to a query against IDbSet<UserEntity>. After querying against IDbSet<UserEntity> I want to convert the UserEntity to a User domain class. Is this possible?
I have in mind to cerate an IQueryable implementation for my User class that internally queries against UserEntity.
public class MappedEntityQuery<TModel, TEntity> : IQueryable<TModel>
{
}

Code First requires the convention to have all IDbSet properties to access the tables to be in the DbContext
That is not true. You don't need to have any set declared in the context if you provide mapping to the entities in the model builder. In your case you should declare mapping through EntityTypeConfiguration<T> and ComplexTypeConfiguration<T> derived classes. You can create any DbSet instance of mapped entity type by calling Set<T>() on the context.
However for this project I am using a Database First approach, which also does not allow to load compose a DbContext using entities from different projects, because you have to specify the Database metadata in one single metadata file (which will be embedded).
That is true only partially. EDMX metadata must be in the single file embedded in the main project but entity classes do not have to if you use your own instead of auto-generated. So your proposed approach should work.
But if you really want to achieve modularity you should not use EDMX. If you decide to add or change any module in the future it would require changing central project as well but that can affect all other modules - it breaks the idea of modularity, doesn't it?

Related

Why can't I use ApplyConfiguration() to add my audit log table (Audit.NET can't find it)?

I have an existing application that is built on Entity Framework Core 2.2.x. It is using modelBuilder.ApplyConfiguration() to associate entities with the data model dynamically. This works for all of the current entities and even my new AuditLog entity as far as the rest of the application is concerned.
However, when I configure Audit.NET's entity framework core provider to log into AuditLog, the data provider cannot write to the database:
The entity type 'AuditLog' was not found. Ensure that the entity type has been added to the model.
I have scoured the internet for solutions to that error, and found that adding this line to my code will cause Audit.NET to find my AuditLog:
modelBuilder.Entity<AuditLog>().ToTable("AuditLog", "Audit");
My code:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Type[] maps = EntityFrameworkReflectionMapping.Get(EntityTypeConfiguration(), BoundAssemblies);
foreach (object instance in maps.Select(Activator.CreateInstance))
modelBuilder.ApplyConfiguration((dynamic)instance);
modelBuilder.Entity<AuditLog>().ToTable("AuditLog", "Audit");
base.OnModelCreating(modelBuilder);
}
Why do I need to add the entity explicitly, when the rest of the system works as-is?
Additionally, the changes are being detected by Audit.NET through entities which are not explicitly added. So the problem seems to be with Audit.NET's entity framework data provider, or how I'm using it.
I would expect that the data provider would respect the modelBuilder.ApplyConfiguration() approach to associating entities.
There are many things that could be causing the exception, but looks like EF is not being able to detect the entity-table relation for your AuditLog.
Look for a wrong connection string, maybe your AuditLog being defined on a different assembly than other entities.
Also try adding the AuditLog entity class within a db set as a property on your DbContext, for example:
public class MyContext : AuditDbContext
{
//...
public DbSet<ModelName> ModelName { get; set; }
}

Map Read from CRUD in EF 6 Fluent API

I've been scouring the net, but haven't found anything useful. I have a POCO class that I want to wire up to a stored procedure in Entity Framework 6.x. I've see how to do it in the Fluent API for Inserts, Updates, and Deletes.... but not for just straight Reading.
I found this: EF 6 Code First Stored Procedure - Read Only, but it looks like it's just a method on some controller somewhere.
Is there a way where I can call the context like I would any other Entity. I.E.,
ctx.Products.Where( p => p.ProductId == productId )?
I would approach this is one of two ways.
Domain / POCO mapping
If the underlying issue is a mismatch between your Entity Framework model POCO's and your (presumably purely logical) domain, I would match the EF model directly to the database schema and them map them across to domain types accordingly. I.e have a separate domain model to your EF poco's. The mapping work previously done by your proc would then be done within the domain mapper.
Abstract DbContext usage behind Repositories
Rather than having consumers directly query the context, you could abstract the context behind entity repositories and map between a SqlQuery calling a proc and your POCO's in the repository methods
E.g. here is some rough code:
public class MyEntityRepository()
{
public ICollection<MyEntity> GetAll()
{
return _myContext.SqlQuery<MyEntity>("exec myProc", params);
}
}
Neither of these options would be quick to implement and introduce into your codebase though.

Resuable Coding with Unit Of Work Pattern in Entity Framework

Lets assume that below code retrieves data from database via Unit Of Work pattern.
Since the GetByID is the common operation, it can be declared inside Repository class.
UnitOfWork w = new UnitOfWork();
w.someRepository.GetByID(10);
What if i need to call GetByID method in 10 seperate files. Should i create an instance of UnitOfWork class and call GetByID in every time or does the code-block below is valid for UnitOfWork pattern?
public class SomeRepositoryProvider {
public tbl_somerepoclass GetByID(int id) {
UnitOfWork w = new UnitOfWork();
return w.someRepository.GetByID(10);
}
}
Generally you shouldn't even need UnitOfWork when you want only to retrieve data from database. UnitOfWork is more like transaction to db - you try to persist some set of data to db in one go - if everyfing goes ok it is saved, if not then everything is rollback. To get entities by ids you should only need Repositories. The best solution I encountered in my practice is to for each entity prepare Repository class and prepre there useful methods. Only if you want to save the data use UnitOfWork. So generally you should use your repostiory like that:
someRepository.GetById(10);
When you instantiate Repository just pass to its constructor proper object needed for the operations - in case of entity framework ver. > 4.0 DbContext.
If you want to add new entity use it like that:
someRepository.Add(newEntity);
unitOfWork.Save();

DbContext with dynamic DbSet

Is it possible to have a DbContext that has only one property of the generic type IDbSet and not a collection of concrete IDbSet e.g. DbSet.
More specifically, i want to create only one generic DbSet where the actual type will be determined dynamically e.g.
public new IDbSet<T> Set<T>() where T : class
{
return context.Set<T>();
}
I don't want to create multiple DbSets e.g.
DbSet<product> Products { get; set; }
...
Actually i tried to use that generic DbSet but there seems to be one problem. The DbContext doesn't create the corresponding tables in the database. So although i can work with the in-memory entity graph, when the time comes to store the entites into the DB an exception is thrown (Invalid object name 'dbo.Product'.)
Is there any way to force the EF to create tables that correspond to dynamicaly creates DbSets?
Yes you can do this.
modelBuilder.Configurations.Add
The DBSet entries will be derived.
If you plan to use POCOs and just build the model this way ok.
So you save Manual DBSet<> declaration...
But if you plan on being more Dynamic without POCOs...
Before you go down the this route, there are a number of things to consider.
Have you selected the right ORM ?
Do you plan on having a POCOs ?
Why is DbSet Products { get; set; } so bad ?
You get a lot of action for that 1 line of code.
What Data access approach you plan to use without types DBSets
Do you plan to use Linq to Entity statements?
do you plan on creating Expression trees for the Dynamic Data access necessary. Since the types arent known at compile time.
Do you plan to use the DB Model cache,?
How will the cache be managed, especially in Web. ASP environments.
There are most likely other issues i did think of off the top of my head.
Constructing the model yourself is a big task. The Linq access is compromised when compile time types/POCOs are NOT used and the model cache and performance become critical management tasks.
The practical side of this task is not to under estimate
Start here bContext.OnModelCreating
Typically, this method is called only once when the first instance of
a derived context is created. The model for that context is then
cached and is for all further instances of the context in the app
domain. This caching can be disabled by setting the ModelCaching
property on the given ModelBuidler, but this can seriously degrade
performance. More control over caching is provided through use of the
DbModelBuilder and DbContext classes directly.
The modelbuilder class
Good Luck

EF 4.2 Code First and DDD Design Concerns

I have several concerns when trying to do DDD development with EF 4.2 (or EF 4.1) code first. I've done some extensive research but haven't come up with concrete answers for my specific concerns. Here are my concerns:
The domain cannot know about the persistence layer, or in other words the domain is completely separate from EF. However, to persist data to the database each entity must be attached to or added to the EF context. I know you are supposed to use factories to create instances of the aggregate roots so the factory could potentially register the created entity with the EF context. This appears to violate DDD rules since the factory is part of the domain and not part of the persistence layer. How should I go about creating and registering entities so that they correctly persist to the database when needed to?
Should an aggregate entity be the one to create it's child entities? What I mean is, if I have an Organization and that Organization has a collection of Employee entities, should Organization have a method such as CreateEmployee or AddEmployee? If not where does creating an Employee entity come in keeping in mind that the Organization aggregate root 'owns' every Employee entity.
When working with EF code first, the IDs (in the form of identity columns in the database) of each entity are automatically handled and should generally never be changed by user code. Since DDD states that the domain is separate from persistence ignorance it seems like exposing the IDs is an odd thing to do in the domain because this implies that the domain should handle assigning unique IDs to newly created entities. Should I be concerned about exposing the ID properties of entities?
I realize these are kind of open ended design questions, but I am trying to do my best to stick to DDD design patterns while using EF as my persistence layer.
Thanks in advance!
On 1: I'm not all that familiar with EF but using the code-first/convention based mapping approach, I'd assume it's not too hard to map POCOs with getters and setters (even keeping that "DbContext with DbSet properties" class in another project shouldn't be that hard). I would not consider the POCOs to be the Aggregate Root. Rather they represent "the state inside an aggregate you want to persist". An example below:
// This is what gets persisted
public class TrainStationState {
public Guid Id { get; set; }
public string FullName { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
// ... more state here
}
// This is what you work with
public class TrainStation : IExpose<TrainStationState> {
TrainStationState _state;
public TrainStation(TrainStationState state) {
_state = state;
//You can also copy into member variables
//the state that's required to make this
//object work (think memento pattern).
//Alternatively you could have a parameter-less
//constructor and an explicit method
//to restore/install state.
}
TrainStationState IExpose.GetState() {
return _state;
//Again, nothing stopping you from
//assembling this "state object"
//manually.
}
public void IncludeInRoute(TrainRoute route) {
route.AddStation(_state.Id, _state.Latitude, _state.Longitude);
}
}
Now, with regard to aggregate life-cycle, there are two main scenario's:
Creating a new aggregate: You could use a factory, factory method, builder, constructor, ... whatever fits your needs. When you need to persist the aggregate, query for its state and persist it (typically this code doesn't reside inside your domain and is pretty generic).
Retrieving an existing aggregate: You could use a repository, a dao, ... whatever fits your needs. It's important to understand that what you are retrieving from persistent storage is a state POCO, which you need to inject into a pristine aggregate (or use it to populate it's private members). This all happens behind the repository/DAO facade. Don't muddle your call-sites with this generic behavior.
On 2: Several things come to mind. Here's a list:
Aggregate Roots are consistency boundaries. What consistency requirements do you see between an Organization and an Employee?
Organization COULD act as a factory of Employee, without mutating the state of Organization.
"Ownership" is not what aggregates are about.
Aggregate Roots generally have methods that create entities within the aggregate. This makes sense because the roots are responsible for enforcing consistency within the aggregate.
On 3: Assign identifiers from the outside, get over it, move on. That does not imply exposing them, though (only in the state POCO).
The main problem with EF-DDD compatibility seems to be how to persist private properties. The solution proposed by Yves seems to be a workaround for the lack of EF power in some cases. For example, you can't really do DDD with Fluent API which requires the state properties to be public.
I've found only mapping with .edmx files allows you to leave Domain Entities pure. It doesn't enforce you to make things publc or add any EF-dependent attributes.
Entities should always be created by some aggregate root. See a great post of Udi Dahan: http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/
Always loading some aggregate and creating entities from there also solves a problem of attaching an entity to EF context. You don't need to attach anything manually in that case. It will get attached automatically because aggregate loaded from the repository is already attached and has a reference to a new entity. While repository interface belongs to the domain, repository implementation belongs to the infrastructure and is aware of EF, contexts, attaching etc.
I tend to treat autogenerated IDs as an implementation detail of the persistent store, that has to be considered by the domain entity but shouldn't be exposed. So I have a private ID property that is mapped to autogenerated column and some another, public ID which is meaningful for the Domain, like Identity Card ID or Passport Number for a Person class. If there is no such meaningful data then I use Guid type which has a great feature of creating (almost) unique identifiers without a need for database calls.
So in this pattern I use those Guid/MeaningfulID to load aggregates from a repository while autogenerated IDs are used internally by database to make a bit faster joins (Guid is not good for that).