I'm using Entity Framework with DDD.
I have the following entities: Person, Customer, Employee
Person is abstract.
Customer and Employee inherit person.
Person has references to the Person Address (List).
Should I have a repository for each type or only for each concrete type? (Just Customer and Employee)
Could I have a repository Person then Customer and Employee repositories depend on it internally to avoid redundant code? (Using DI by constructor injection)
This isn't meant to give a complete application structure, but a good basis for designing what you may need when working with different Repositories and Inheritance etc.
// Model stuff...
public interface IBaseEntity
{
[Key]
int Id { get; set; }
}
public abstract class BaseEntity : IBaseEntity
{
[Key]
public virtual int Id { get; set; }
// Add some extra fields for all Models that use BaseEntity
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Display(Name = "Last Modified")]
public virtual DateTime LastModified { get; set; }
[ConcurrencyCheck]
[Timestamp]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public virtual byte[] Timestamp { get; set; }
}
public class Person : BaseEntity
{
// Person Model here...
}
public class Employee : Person
{
// Extra Employee Model items here
}
public class Customer : Person
{
// Extra Customer Model items here
}
// End Model stuff
// Repository stuff...
public interface IRepository<T> where T : class
{
IQueryable<T> GetAll();
T GetById(int? id);
T Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(int id);
void Commit(); // To save changes rather than performing a save after each Add/Update/Delete etc.
}
public class EFRepository<T> : IRepository<T> where T : class, IBaseEntity
{
public virtual IQueryable<T> GetAll()
{
return DbSet.AsQueryable<T>();
}
public virtual T GetById(int? id)
{
var item = DbSet.Find(id);
return item;
}
public virtual T Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
// SaveChanges() - removed from each DbSet, so can call on all changes in one transaction.
// Using Unit Of Work Pattern. Can still use it here though if wished.
return entity;
}
// And so on for each storage method.
}
public interface IEmployeeRepository: IRepository<Employee>
public interface ICustomerRepository: IRepository<Customer>
public class EmployeeRepository : EFRepository<Employee>, IEmployeeRepository
public class CustomerRepository : EFRepository<Customer>, ICustomerRepository
// End Repository stuff
Basically you can add new Models and their Repositories by declaring the interfaces and classes with virtually nothing inside them. Everything inherits from the base crud functionality etc.
You only need to add new methods for getting records from the database in special cases for the Model being added - FindEmployeeByHairColor(color) for example, all other EF Gets, Finds etc. are the same regardless of the type.
This can get very deep, using Services to provide access to the core methods in the Repositories, add the Unit Of Work pattern to combine several DbSets into one transaction, and so on.
But using this type of layout allows me to inject into each layer the particular Repository/Service I wish to use, and keeps all logic in a single class that is re-used throughout everything that uses similar logic.
Hope this helps.
I would just have repositories for Customer and Employee.
If there is shared logic between these encapsulate it in an abstract base class and have the repositories inherit from it.
So you would end up with this sort of structure:
public interface ICustomerRepo { }
public interface IEmployeeRepo { }
public abstract class PersonRepoBase<T> { }
public class CustomerRepo : PersonRepoBase<Customer>, ICustomerRepo { }
public class EmployeeRepo : PersonRepoBase<Employee>, IEmployeeRepo { }
Related
I am trying to design my application architecture using ado.net with sql server. I am consider to use threee layers as follows:
Presentation Layer -> Business Layer (BAL) -> Data access Layer (DAL)
Entities for sample objects like Employee, Department etc..
I am trying to use interfaces as a contracts for some of my classes. My current issue is that i see some of the methods are common between BAL and DAL objects like: Add, Remove, GetAll therefore i decided to create interfaces to implement such things however when using from BAL classes i need to have it like void Add(Employee) but in DAL void Add(string name); therefore i splitted almost same interfaces on DAL and BAL (i do not like it because it seems to be somehow duplicated). Next issue is when want to use my code at the StickTogether class i am not able to call for instance _employee.Department = _department; I know it's because Department property should be in RepositoryBal interface but then simple entity Department would need to implement such interface which i dont want to do because as far as i read entities are just simple repeesentation of specific object. Could you tell me - best show on example how you would create such architecture or modify my to have something better than what i have right now. Below find my full code i am working on. How this could be fixed?
Please note i also start to prepare this code for dependency which will be helpfull for moc tests.
Appreciate your answers with proposed fixed solution based on my code.
public class StickTogether
{
private readonly IRepositoryBal<Employee> _employee;
private readonly IRepositoryBal<Department> _department;
public StickTogether(IRepositoryBal<Employee> employee, IRepositoryBal<Department> department)
{
_employee = employee;
_department = department;
}
public void Create()
{
_employee.Add(new Employee());
_department.Add(new Department());
_employee.Department = _department; //not accessible which has a sense
}
}
public interface IEntity
{
int Id { get; set; }
}
public class Employee : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public Department Department { get; set; }
}
public class Department : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
public interface IRepositoryDal<T> where T : IEntity
{
void Add(string name);
void Delete(int id);
IEnumerable GetAll();
}
public interface IRepositoryBal<T> where T : IEntity
{
void Add(T entity);
void Delete(T entity);
IEnumerable<T> GetAll();
}
internal class DepartmentBal : IRepositoryBal<Department>
{
private readonly IRepositoryDal<Department> _departmentDal;
public DepartmentBal(IRepositoryDal<Department> department)
{
_departmentDal = department;
}
public void Add(Department entity)
{
_departmentDal.Add(entity.Name);
}
public void Delete(Department entity)
{
_departmentDal.Delete(entity.Id);
}
public IEnumerable<Department> GetAll()
{
return (IEnumerable<Department>)_departmentDal.GetAll();
}
}
public class DepartmentDal : IRepositoryDal<Department>
{
public void Add(string name)
{
//call sql server stored procedure to add department;
}
public void Delete(int id)
{
//call sql server stored procedure to delete department by id;
}
public IEnumerable GetAll()
{
//call sql server stored procedure to return all employees;
return null;
}
}
internal class EmployeeBal : IRepositoryBal<Employee>
{
private readonly IRepositoryDal<Employee> _employeeDal;
public EmployeeBal(IRepositoryDal<Employee> employee)
{
_employeeDal = employee;
}
public void Add(Employee entity)
{
_employeeDal.Add(entity.Name);
}
public void Delete(Employee entity)
{
_employeeDal.Delete(entity.Id);
}
public IEnumerable<Employee> GetAll()
{
return (IEnumerable<Employee>) _employeeDal.GetAll();
}
}
public class EmployeeDal : IRepositoryDal<Employee>
{
public void Add(string name)
{
//call sql server stored procedure to add employee;
}
public void Delete(int id)
{
//call sql server stored procedure to delete employee by id;
}
public IEnumerable GetAll()
{
//call sql server stored procedure to return all employee;
return null;
}
}
The 3 layer (anti pattern?) is a red herring here, you're essentially talking a dependency injection. pattern. These become difficult to manage manually. I'd suggest you implement a DI framework like Simple Injector or Unity.
I am trying to use interfaces as a contracts for some of my classes.
Why some of your classes? If your going to implement dependency injection then implement it on all classes.
My current issue is that i see some of the methods are common between
BAL and DAL objects like: Add, Remove, GetAll therefore i decided to
create interfaces to implement such thing
Here's your first mistake. You've decomposed based on functionality, not responsibility. Just because something has a similar method signature does not mean they should be related. A Customer business object has a very different responsibility to a Customer data object. Remember favour composition over inheritance.
however when using from BAL classes i need to have it like void
Add(Employee) but in DAL void Add(string name);
This just highlights the above, you've made the decision that because the methods are called "Add" their the same, their obviously not.
I would say you should implement an interface for each object, dont' try and relate unrelated object, then configure this using a DI framework, then inject them. Try not to blur your lines and keep your seperations clear. Remember you want high cohesion and low coupling.
To give some examples I'd forget about your IRepositoryBal and the generics altogether and just simplify the whole thing:
//your going to struggle to do DI with internal classes, make them public
public class EmployeeBal : IEmployeeBal
{
//
}
public interface IEmployeeBal
{
void Add(Employee entity);
void Delete(Employee entity);
IEnumerable<Employee> GetAll();
Department Department {get; set;}
}
public class StickTogether
{
private readonly IEmployeeBal _employee;
private readonly IDepartmentBal _department;
public StickTogether(IEmployeeBal employee, IDepartmentBal department)
{
_employee = employee;
_department = department;
}
public void Create()
{
_employee.Add(new Employee());
_department.Add(new Department());
_employee.Department = _department; //not accessible which has a sense
}
}
You then configure these in your DI framework, for example in simple Injector you would do:
Container _defaultContainer = new Container();
_defaultContainer.Register<IEmployeeBal, EmployeeBal>();
_defaultContainer.Register<IDepartmentBal, DepartmentBal>();
_defaultContainer.Register<IDepartmentDal, DepartmentDal>();
//..etc.
you then get your parent instance (only!) thus:
IEmployeeBal entryPoint = _defaultContainer.GetInstance<IEmployeeBal>();
the DI framework does the rest and all your dependencies are decoupled.
aLets have a simple scenario:
public interface IMember
{
string Name { get; set; }
}
public class MemberEF6Impl : IMember
{
//some annotations...
public string Name { get; set; }
}
public class MemberVMImpl : IMember
{
//some other annotations...
public string Name { get; set; }
//some functionality...
}
I have two concrete implementation of all interfaces in our programm. One implementation especially for database migration, one for our viewmodel. Now I want to realize the factory-pattern and add one more interface and two more concrete implementations of it:
public interface IRepository
{
ICollection<TModel> GetAll<TModel>() where TModel : class;
//some more functionality...
}
public class RepositoryEF6Impl : IRepository
{
protected readonly DbContext context;
public RepositoryEF6Impl(DbContext context)
{
this.context = context;
}
public ICollection<TModel> GetAll<TModel>() where TModel : class
{
return context.Set<TModel>().ToList();
}
//some more functionality...
}
Now I can use the repository straight forward as follows:
IRepository repo = new RepositoryEF6Impl(context);
repo.GetAll<MemberEF6Impl>();
So far so good. But I want to use it this way:
IRepository repo = new RepositoryEF6Impl(context);
repo.GetAll<IMember>(); //note the difference
The problem is that in the database there is no IMember, but a MemberEF6Impl.
Why I want to use it this way:
Because we have different concrete classes for databse stuff and for viewmodel, I have to create a 2nd repository as well for viewmodel, which is only a layer between the concrete VMImpl class and the EF6 repository.
public class RepositoryVMImpl : IRepository
{
protected readonly IRepository repository;
public RepositoryVMImpl(IRepository repository)
{
this.repository = repository;
}
public ICollection<TModel> GetAll<TModel>() where TModel : class
{
return repository.GetAll<TModel>();
}
}
Is there a way to achive this?
My suggestion is to use single repository, but with some method overloading for projecting the requested generic type.
Method overload:
public ICollection<TProjection> GetAll<TModel, TProjection>(Expression<Func<TModel, TProjection>> projection)
{
return context.Set<TModel>().Select(projection).ToList();
}
then you can use the method like this, which will give control over the return type.
repository.GetAll<MemberEF6Impl, IMember>(memberEF => new MemberVMImp { ... })
If you still need the EF entity model as a result type you can use your current method:
repository.GetAll<MemberEF6Impl>();
More information about EF projections: https://www.tektutorialshub.com/projection-queries-entity-framework/
Also Automapper provides such functionality - it can save you some time. You should check it out.
We are using EF6 in our MVC 4 application, so we created an abstract class for Business Objects
So, We have a generic abstract class as the following :
public abstract class Repository<TEntity, TIdentifier> : IRepository<TEntity, TIdentifier> where TEntity : class { ... }
in our application's BusinessLayer we have several classes (one class per an Entity) that implement above class.
e.g: as the following
//Authorization is an entity here
public class AuthorizationBusinessObject : MD.EntityFramework.Repository.Repository<Authorization, int>
{
...
}
We need to have a BaseBusinessObject for above classes.
Now, my question is here; how we can have a BaseBusinessObject class for above classes?
Edit :
Well, Repository<> is a base class for BusinessObjects, isn't it?
Actually, We need a non generic base class for BusinessObjects
Why?
We are using web API services in our MVC 4 application. in each web api controller we have to have the same actions as the following, only BusinessObject is different. So, if we could have a base business object, we could implement the following Actions in base web api controller.
// Setting is an Entity
private readonly SettingBusinessObject _settingBusinessObject;
public SettingController()
{
_settingBusinessObject = new SettingBusinessObject(Entities);
}
public Setting Get(int id)
{
return _settingBusinessObject.SelectBy(id);
}
public List<Setting> Get(IEnumerable<int> ids)
{
return _settingBusinessObject.SelectAll(ids).ToList();
}
public Setting Put(Setting setting)
{
return _settingBusinessObject.Update(setting);
}
public List<Setting> Put(List<Setting> entities)
{
List<Setting> userList = new List<Setting>();
userList.AddRange(entities.Select(_settingBusinessObject.Update));
return userList;
}
public Setting Post(Setting entity)
{
return _settingBusinessObject.Insert(entity);
}
public List<Setting> Post(List<Setting> entities)
{
List<Setting> userList = new List<Setting>();
userList.AddRange(entities.Select(_settingBusinessObject.Insert));
return userList;
}
public void Delete(int id)
{
_settingBusinessObject.Delete(id);
}
public void Delete(List<int> ids)
{
_settingBusinessObject.Delete(ids);
}
Why can't the BaseBusinessObject class also be generic?
public abstract class BaseBusinessObject<TEntity, TIdentifier> : Repository<TEntity, TIdentifier>
{
... base stuff here
}
public class AuthorizationBusinessObject : BaseBusinessObject<Authorization, int>
{
}
It's worth noting, though, that layering lots of per-entity stuff on top of EF can add a ton of boilerplate with little real benefit. It might be wortwhile considering whether just using EF directly will get you what you need or whether your business object classes should be organized around logical sets of operations rather than around individual entities.
I have a generic repository that I use for common things such as FetchAllData, GetbyID and so on... Anyway, I want to include a Deactivate(T Entity) method so that instead of deleting data I will just turn their status off so the user will not see the data, but I can see it whenever I need. Basically, something similar to:
public interface IGenericRepository<T> where T : class {
...somecode
}
public class GenericRepository<T> : IGenericRepository<T> where T : class {
public T GetbyID(int id) { ... }
public void Deactivate(T entity) {
entity.stat = 0; // I know that this stat is common in all tables. However,
// my problem is that I don't know how to make appear stat
// in IntelliSense.
}
}
I know that this can be done, but I how do I do it?
Declare a interface:
public interface IDeactivatable {
int stats { get; set; }
}
Then your entities must derive from IDeactivatable.
Tip: You can add a generic type constraint too:
[...] IGenericRepository<T> where T : class, IDeactivatable [...]
i am pretty new to the repository design pattern and i have reached a dead end while trying to implement it, with regards to inheritance.
I am not sure even if i started in the right direction.
So basically i will have an abstract base class Product, with id and imagePath for instance, and will have several products which inherit from this.
namespace Common
{
public abstract class Product
{
public int Id { get; set; }
public string ImgPath { get; set; }
}
public class Scale : Product
{
public int AdditionalProperty { get; set; }
}
}
Now the repositories are as follows:
public class BaseRepository
{
protected TEstEntities1 _dataContext = new TEstEntities1();
public BaseRepository()
{
_dataContext = new TEstEntities1();
}
}
public interface IProductRepository
{
Common.Product Get(int id);
void Add(Common.Product p);
void Update(Common.Product p);
List<Common.Product> ListAll();
}
public class ProductRepository : BaseRepository, IProductRepository
{
public Common.Product Get(int id)
{
throw new NotImplementedException();
}
public void Add(Common.Product p)
{
throw new NotImplementedException();
}
public void Update(Common.Product p)
{
throw new NotImplementedException();
}
public List<Common.Product> ListAll()
{
throw new NotImplementedException();
}
}
My problem is as follows: how do i integrate operations regarding Scale ? It seems a bad idea to add something like Add(Common.Scale s) to the IProductRepository. It seems like a bad idea to see inside the Add(Common.Product p) which type of Product i try to add, then cast to it, then add.
I guess that if i were to describe this problem more thoroughly, I want to repeat as few code as possible, to somehow isolate base product adding/removing code in the product repository, and somehow put e.g. Scale specific code for adding/removing inside another class, or method.
A more thorough approach of mine has been this one:
public interface IProductRepository<T> where T : Common.Product
{
T Get(int id);
void Add(T p);
void Delete(T p);
}
public abstract class ProductRepository : BaseRepository
{
protected void Add(Common.Product p)
{
_dataContext.AddToProduct(new Product { Id = p.Id, Image = p.ImgPath });
_dataContext.AcceptAllChanges();
}
protected void Delete(Common.Product p)
{
var c = _dataContext.Product.Where(x => x.Id == p.Id).FirstOrDefault();
_dataContext.DeleteObject(c);
_dataContext.AcceptAllChanges();
}
protected Product Get(int id)
{
return _dataContext.Product.Where(x => x.Id == id).FirstOrDefault();
}
}
public class CantarRepository : ProductRepository, IProductRepository<Common.Scale>
{
public void Add(Common.Scale p)
{
base.Add(p);
_dataContext.Scale.AddObject
(new Scale { ProductId = p.Id, AdditionalProperty = p.AdditionalProperty });
_dataContext.AcceptAllChanges();
}
public void Delete(Common.Scale p)
{
var c = _dataContext.Scale.Where(x => x.ProductId == p.Id);
_dataContext.DeleteObject(c);
_dataContext.AcceptAllChanges();
base.Delete(p);
}
public new Common.Scale Get(int id)
{
var p = base.Get(id);
return new Common.Scale
{
Id = p.Id,
ImgPath = p.Image,
AdditionalProperty = _dataContext.Scale.Where
(c => c.ProductId == id).FirstOrDefault().AdditionalProperty
};
}
}
Unfortunatelly this falls short for one reason.
If i use a factory pattern to return an IProductRepository and inside it i instantiate with IProductRepository this will not work because of covariance and contravariance, and IProductRepository can't be contravariant and covariant at the same time, and splitting the methods into two interfaces seems counterintuitive and cumbersome.
I suspect i will need the factory pattern in order to have a base class interface returned, but i am open to suggestions on this as well. As i've said, i am very newbie regarding the repo pattern.
I am curious as to what i am doing wrong, how i can solve this, and how can i implement this better.
Thanks.
You are using inheritance incorrectly. You cannot treat Scale as a (is-a) Product if the important difference is additional properties - that makes the exposed interface of Scale different than Product, and at that point inheritance simply gets in your way. Use inheritance to share behavior, not properties.
What problem are you trying to solve with your use of inheritance?
I want to repeat as few code as
possible
Wouldn't it be better to have a little duplication in order to get things done, rather than spin your wheels trying to work with an implausible design?
Also, this is all you are sharing with your inheritance:
public int Id { get; set; }
public string ImgPath { get; set; }
Repeating the definition of two auto-implemented properties almost doesn't even qualify as duplication, it most certainly is not an issue to be concerned about.
Misusing inheritance, however, is fairly grievous. The next person to maintain your app will curse you for it.
So basically i will have an abstract
base class Product, with id and
imagePath for instance, and will have
several products which inherit from
this.
So when you add new types of products you will have to extend an inheritance hierarchy? That seems like a bad idea.
I'm not a big fan of generic repository but after looking at your code I think you should use it:
public interface IEntity
{
int Id { get; }
}
public interface IRepository<T> where T : class, IEntity
{
IQueryable<T> GetQuery();
T Get(int id);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
}
implementation:
public Repository<T> where T : class, IEntity
{
private ObjectSet<T> _set; // or DbSet
private ObjectContext _context; // or DbContext
public Repository(ObjectContext context) // or DbContext
{
_context = context;
_set = context.CreateObjectSet<T>(); // _context.Set<T>() for DbContext
}
public IQueryable<T> GetQuery()
{
return _set;
}
public T Get(int id)
{
return _set.SingleOrDefault(e => e.Id == id);
}
public void Add (T entity)
{
_set.AddObject(entity);
}
public void Update(T entity)
{
_set.Attach(entity);
context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
// or context.Entry(entity).State = EntityState.Modified; for DbContext
}
public void Delete(entity)
{
_set.Attach(entity);
_set.DeleteObject(entity);
}
}
There is NO AcceptAllChanges because it will reset ObjectStateManager and your changes will never be saved. There is no recreation of objects because it doesn't make sense.
Using this repository is as simple as:
var repo = new BaseRepository<Product>(context);
repo.Add(new Product() { ... });
repo.Add(new Scale() { ... }); // yes this works because derived entities are handled by the same set
context.Save();
I recently implemented something like this. (Using your sample types names) I have a single ProductRepository which knows how to persist/unpersist all Product subtypes.
Ultimately, your backing data store will have to have the ability to store the various subtypes and any properties which they introduce. Your repository type will also have to know how to take advantage of those features for each given subtype. Therefore, each time you add a subtype, you will have work involved in, for example, adding table columns to your backing data store to hold properties it may introduce. This implies that you will also need to make the appropriate changes to your repository type. It seems easiest, therefore, to examine the type of the entity when passed to your repository type and throw an exception if it is not a supported type since there's nothing else your repository will be able to do with it. Similarly, when retrieving the list of entities, the repository will have to know how to retrieve each entity subtype and construct an instance. Since these all derive from Product, they can all form items an in IEnumerable<Product> return value.