Wrapping EntityFrameWork with IDal<T> interface - c#

I want to wrap my EntityFrameWork class with IDal<T> interface with CRUD operations only.
I thought to create BL Data Model corresponding to each Entity
Meaning if I have TempEntity I'll create TempBlObj and interface IDal<TempBlObj>
Are there any guideliness to complete such task?
I had a problem implementing Save(TempBlObj)
as saving in entity is done by:
mDbEntities.SaveChanges();
and this relays on change that had been done on entity reference.
Any solutions?
Update
I'm doing all this in order to mock my IDal<T> interface
For example in order to change TempEntity.status
I'll have to create a concrete method ChangeStatus() instead of generic CRUD : Save(BlObj item)
as save with entity is done like
..take reference to some entity, do some change.. and
mMamDbEntities.SaveChanges();
I tried to add BlObjects in order to loosen dependency between the Bl and concrete EntityFW
More General:
When using ORM, what is the best practice for loose cupling, working with IDal<T> intreface (CRUD operations) ?

The responsibility of saving an entity should not be the job of entity itself. It is a bad idea.
You can consider implementing repository pattern in your situation.

There are several facts I try to keep in mind when planning a repository for my system:
O/RM is something that helps me to implement storage-unaware entities. That means that I do not divide business entities and DB entities specifically. I have a User entity - and ORM should persist it no matter how, and I'm not going to introduce additional layers here.
I'd start with less restrictive interface:
interface IDal {
T Get<T>(id);
void Save(object o); //or T, if needed
IQueryable<T> Query<T>();
}
And - it could be mocked pretty fine (sample using Moq).
var users = new List<User>(){ /* Users here */}
var mockedRepository = new Mock<IRepository>();
//getup GET
mockedRepository.Setup(
self => self.Get<User>( It.IsAny<int>() )
.Returns( (int id) => _users.First(u => u.Id == id) );

Related

Where do I put my mapping logic?

I have a domain model, a repository and entity framework. I don't want my domain tied to EF or the persistence layer in general.
So I created a repository to keep things like db.Users.Where(u => u.Team == "MyTeam") out of my domain.
After implementing the generic repository pattern if I want a list of users on a particular team I use UserRepository.GetUsersByTeam("MyTeam").
The problem is my UserRepository is returning IEnumerable<EntityFrameworkUser>, instead of IEnumerable<DomainUser>, and in order to return IEnumerable<DomainUser> I need to map DomainUser to EntityFrameworkUser somewhere.
So where specifically do you map from the EntityFrameworkUser class to the DomainUser class?
Should the repository encapsulate the mapping logic in addition to the query logic?
If I want a collection of domain user objects what does the call stack look like for UserRepository.GetUsersByTeam("MyTeam") look like?
Searching has only found me general responses that usually quote Martin Fowler. I need a concrete example to refer to.
The problem is my UserRepository is returning an entity framework User DbSet
That shouldn't be the return type, because that would introduce coupling. You can still return that type, but it should be polymorphically interpreted as a different type.
So while you may be doing something like this in your repository:
return db.Users;
The return type shouldn't be that implementing type (DbSet<User>?), but something more generic:
public IQueryable<User> GetUsers()
{
return db.Users;
}
The "EF objects" are being used throughout the domain, but the domain doesn't know or care about that. The domain sees it as a queryable collection of User models.
If you want to keep domain object separately - keep them separately. If you repository returns objects from persistent layer, then it opens door for over-posting issues (it especially dangerous when front-end uses the same objects). I would move mapping logic into another class and use it in your repositories.
Automapper is very popular library for mapping different object, for example Domain object to DTO and vise versa. You can inject Automapper into your repositories and use it to map IEnumerable<EntityFrameworkUser> to IEnumerable<DomainUser>. First register mapping
Mapper.CreateMap<EntityFrameworkUser, DomainUser>();
Then call it from your repository
return Mapper.Map<IEnumerable<EntityFrameworkUser>, IEnumerable<DomainUser>>(users);
If the purpose of the method in question is simply to always return all of the members of the specified team, and you're never going to apply additional clauses to the result, you could change the return type of the UserRepostory.GetUsersByTeam() method from the EF DbSet<User> type to List<User>, then change the return statement to return db.Users.Where(u => u.Team == "MyTeam").ToList().
You'll no longer get the EF objects out of the repository level.

Use repository without Entity Framework

I try to figure out how to implement the repository pattern WITHOUT Entity Framework. I need to use the ADO.NET(disconnected) implementation,(withot DbContext). I know if it is possible.
I have one interface of Repository like it:
public interface IRepository<T>
{
void Add(T newEntity);
void Remove(T Entity);
void Update(T Entity);
IQueryable<T> GetAll();
T Get(object key);
void SaveChanges();
}
So, I just need to know how use it with ADO.NET connection and Mapper or other thing.
Your question is about the repository pattern, however your sample looks more like writing a custom linq provider.
This is actually rather complex thing, and what i think you actually need is to really use the repository pattern, where you have methods like GetCar(int Id) that you then implement specifically using what ever framwork you want.
The diffrence is that with a linq provider like EF, you're exposing the ability for callers to write write any query they want. However, technically this breaks the repository pattern. The idea with the Repo pattern is to contain all the queries in a single class that then expose methods for doing only what the application needs. This way you don't get queries all over your code, and you can implement only the operations your application needs.
In other words, EF is not really an example of the repository pattern, it's a way to talk to the database and create classes that represent the entities in the database. Typically you'd use EF or something similar inside your repository and possibly expose the actual entity types for the outside to use.
Now, writing a custom linq provider is still interesting and if you want to do it, check out this series:
http://www.jacopretorius.net/2010/01/implementing-a-custom-linq-provider.html

How can I decouple the EF POCO from the generic IRepository in this pattern?

I currently have a Repository/UnitOfWork pattern down. However, there is one hard coupling that I am unable to figure out how I can get rid of.
This is an overview of my pattern:
Business Logic Layer
IRepository
Used as type contraint
IRepository< TModel, TDTO >
Implements IRepository
General CRUD methods
IEmployeeRepository< TModel >
Implements IRepository< TModel, EmployeeDTO >
Some employee specific methods
IUnitOfWork
Getter for repositories
Save method
IEntityWithId
Interface to force (and expose) DTOs and EF POCOs to have a Int32 field called ID
Used as type contraints
EmployeeDTO (Mapped with AutoMapper in the implemented EmployeeRepository)
DTO entity used in the core project and (to come) test project
Data Layer (Injected with Ninject)
UnitOfWork
Implementation of IUnitOfWork based on Entity Framework
EmployeesRepository
Implementation of IEmployeeRepository< TModel >
Employee
EF POCO
Core
EmployeesController
Parametered constructer EmployeesController(IUnitOfWork unitOfWork)
IUnitOfWork is injected with a Ninject module as a UnitOfWork (from Data layer)
Those are the problem methods in my generic IRepository interface.
TDTO Find(Expression<Func<TModel, bool>> filter);
and
IEnumerable<TDTO> FindAll(Expression<Func<TModel, bool>> filter);
As you can see, there is TModel in there, which is used to build up an expression to filter results. I COULD do something like using an expression on the DTO, but that would require a complete list of employees mapped to DTOs (aka it wouldnt generate a SQL filter but it would filter a SELECT * FROM Employee result list). So this isn't a good option.
The other, more viable but not optimal solution is to use dynamic LINQ. That way, I can pass a simple string in the Find / FindAll methods and get rid of the TModel requirement. However, this would means that refactoring becomes annoying since it fills the code with magic strings.
Just as I posted this, I think I figured out where my problem is.
Find() and FindAll() shouldn't even exist. I should write more specific methods like FindEmployeeByName(string name) in the IEmployeeRepository, then implement it like so :
EmployeeDTO FindEmployeeByName(string name)
{
return Mapper.Map<EmployeeDTO>(dbSet.Where(o=>o.name.Contains(name)).FirstOfDefault());
}
Can anyone confirm this is a proper way to do it? Or suggest something even better?
Edit
Also, if I want to keep Find(Expression...) and FindAll(Expression...) methods, I can, but they are just in the Data layer and used by implemented methods to avoid repeated code. But they should not be used in controllers as they requires knowledge of the underlaying data structure, beyond my Business Logic. That said, they can be implemented in a BaseRepository< TModel > (That I already have but did not mention to keep things more simple) and make EmployeesRepository an extention of BaseRepository. That way, every Repository already have those generic-like method that are Model-Aware.
Not sure if I explained that properly. Let me know if it's unclear and I'll try to edit this and make it better.
Another way to do this is to make your data layer depend on the business layer and have your repository "project" entities into your business objects (DTO's). This way your BL is at the bottom and UI and Data depend on it, but UI and Data do not depend on each other.
This is the method espoused by Mark Seemann in his book on Dependency Injection.

Repository Pattern: How to implement a basic Repository including a predicate in C#?

I am new to repositories. I just read about implementing predicates and a Unit of Work (Fowler). I have seen repository interfaces like the following:
public interface IRepository<ET> {
ET Add( ET entity);
ET Remove( int id);
ET Get( int id);
IList<ET> Get(Expression<Func<T, bool>> predicate);
}
Of course the Unit of Work would inject a data context (Microsoft fan) to the new repository, where the Unit of Work would have a .Save() method, calling Save on all data contexts.
There's no Edit method, so I assume you can modify any Entity that pops out of the Repository then call save changes on the Unit of Work.
Is this correct? Leaky? What am I missing? Do methods of OrderBy need not ever be in a Repository? Should Paging (.Skip().Take()) somehow be implemented in the predicate?
Links to example code out there would be fantastic, especially how to implement the predicate in a repository.
if you are referring Entity Framework
i would you suggest you read this: Link
Update:
I am not a expert in repository pattern, however i do using it in my project now. a part form performance, following is the benefits that i find from this design pattern:
1, Simplify CRUD operation implementations for all entities.
with one interface:
public interface IDataRepository<T> where T : class
then you will be able to replicate others very easily and fast
public class EntityOneRepository : IDataRepository<EntityOne>
public class EntityTwoRepository : IDataRepository<EntityTwo>
2, Keeps my code dry.
some entities may have their own method for data manipulation. (i.e. store procedure)
you can extend it easily without touching other repositories.
public interface IDonationRepository : IDataRepository<Donation>
{
//method one
//method two
//....
}
for the Paging, it can be either done by Skip() and take(), or you can define your own SP in database then call it via EF4. in that case you will benefit from database sp caching as well.
Some time, keeping the code clean and logically readable is also important for a better app structure.
The repository interface you've presented is a very easy-to-use CRUD interface that can work well in many types of applications. In general, I'd rather not have paging and sorting parameters or options on my repository, instead I'd rather return an IQueryable and let callers compose those types of operations into the query (as long as you are IQueryable, a technology like EF or nHibernate can translate those operators into SQL - if you fall back to IList or IEnumerable it's all in memory operations).
Although I avoid paging and sorting I might have more specific operations on a repository to shield business logic from some details. For example, I might extend IEmployeeRepository from IRepository and add a GetManagers method, or something similar to hide the Where expression needed in the query. It all depends on the application and complexity level.
One important note on this sentence in your post:
Of course the Unit of Work would
inject a data context (Microsoft fan)
to the new repository, where the Unit
of Work would have a .Save() method,
calling Save on all data contexts.
Make sure you are using a single data context/object context inside each unit of work, because a context is essentially the underlying unit of work. If you are using multiple contexts in the same logic transaction then you'd effectively have multiple units of work.
I have a couple sample implementations in this project:
http://odetocode.com/downloads/employeetimecards.zip
The code might make more sense if you read this accompanying article:
http://msdn.microsoft.com/en-us/library/ff714955.aspx
Hope that helps,

ASP.NET MVC: How many repositories?

I am in the process is designing a website in ASP.NET MVC and am perhaps a little confused as to the exact nature of a repository.
Following the NerdDinner example, my site should have one repository which serves up the entities as I need them. However, I have also heard that you should have different repositorys that deal with specific sets of related entities....?
In the case of my site, there will be a number of entities (around 15 tables) yet the majority are all related. Is it ok / advisable to have one repository that contains all the methods that I'll need for pulling / updating / deleting etc or should I split them down?
I use a generic repository which is plenty for many entities.
For a more complex one, I simply extend this with what's needed. The best of both worlds really.
In domain driven design, there's a rule that repositories are per aggregate root. You can read more about it here.
The more I read, the more I think that NerdDinner is too often seen as a collection of good practices, while it's absolutely not (see here for a discussion of, particularly, NerdDinner repository). That's why people often blame other MS examples like Oxite (and here:
Developers will flock to it, praise
it, and blindly accept it as gospel
because it comes from Microsoft (it's
already well on its way). Sadly, any
developer which adopts its spirit will
be left with an unmaintainble,
untestable and unreadable mess
).
If you use a generic repository which accepts types then I don't see any reason to use more than one.
we use an interface like this:
public interface IRepository
{
void Save<ENTITY>(ENTITY entity)
where ENTITY : Entity;
void Delete<ENTITY>(ENTITY entity)
where ENTITY : Entity;
ENTITY Load<ENTITY>(int id)
where ENTITY : Entity;
IQueryable<ENTITY> Query<ENTITY>()
where ENTITY : Entity;
IList<ENTITY> GetAll<ENTITY>()
where ENTITY : Entity;
IQueryable<ENTITY> Query<ENTITY>(IDomainQuery<ENTITY> whereQuery)
where ENTITY : Entity;
ENTITY Get<ENTITY>(int id) where ENTITY : Entity;
IList<ENTITY> GetObjectsForIds<ENTITY>(string ids) where ENTITY : Entity;
void Flush();
}
then use in code like this:
var returnedObjects = repository.GetAll<ObjectClass>();
var singleObject = repository.Get<ObjectClass>(id);
I create a repository for each data object.
For example, a simple library database could contain the following repositories:
AuthorRepository
BookRepository
PublisherRepository
I think perhaps the verbiage of what is a repository might be confusing you. To me a repository is the data storage (ie; MS SQL Database) of where your data is being stored into.
Following the Repository Pattern I recommend setting up a single respository for each datastore. Most of my projects I use MS SQL so I create a Repository for that DB (I like using Subsonic for my DAL/ORM and it also implements the Repositry pattern and the ActiveRecord pattern) then I create Factories for each table. This lets me wrap up the Subsonic ActiveREcord classes and gives me abstraction.
Hope thats helpfull, perhaps...
You should not create Repositories per each table. As queen3 said, you should create Repository per aggregate root. Like, if Products can have a Category, Category Repository should be a nested class of Products. Follow the domain logic relationship than domain objects.
Queen3 is right, you can follow that Aggregate Root theory. I basically group my repository not thinking in Entities but how they group logically in the application I'm building.
For example:
CustomersRepository
OrdersRepository
...
In CustomerRepository I would put methods for GetCustomers, GetCustomer, AddCustomer, DeleteCustomer, AddCustomerContact, DeleteCustomerContact.
In OrdersRepository I would put methods for GetOrders, GetOrder, AddOrder, CancelOrder, CloneOrder, AddOrderDetail, DeleteOrderDetail and so on.
I tend to use a repository per related group of entitites. i.e orderrepository might have:
Order, and OrderDetail.
and would have another for, say, Customer, CustomerProfile, etc.
This keeps the repository classes neat.
Davy

Categories

Resources