I am trying to create a generic base repository for my Linq2Sql entities. I'd like to implement a generic FindAll() method like so.
class BaseRepository<T> : IBaseRepository<T>
{
private readonly FooDataContext _ctx = new FooDataContext();
public IQueryable<T> FindAll()
{
return _ctx.T;
}
public void Add(T entity)
{
_ctx.T.InsertOnSubmit(entity);
}
public void Save()
{
_ctx.SubmitChanges();
}
}
Is there any way to do this without having to use reflection and create slowdown that would make it virtually worthless?
DataContext has what you need in it already.
public IQueryable<T> FindAll()
{
return _ctx.GetTable<T>();
}
public void Add(T entity)
{
_ctx.GetTable<T>().InsertOnSubmit(entity);
}
If you use an in-memory storage system to cache the reflected attributes of a specific type after the first use, you may not have a "virtually worthless" situation at all. In fact, without testing it, you don't really know that the reflection solution would be a problem, do you? (Much of .NET uses reflection and people don't see slowdown in those scenarios. Serialization is one of them.)
This should work:
public IQueryable<T> FindAll()
{
return _ctx.GetTable<T>();
}
Related
I'm trying to use Automapper projections on Entity Framework IQueryables.
On application start, I create and add all my mapping profiles which create maps with the non-static CreateMap method.
All those profiles are registered within my IoC container.
I get the missing mapping exception although I see the mapping profile in the instance of my mappingConfiguration.
What could be the problem? Am I missing something? I'm using Automapper 4.2.1
I've noticed that when adding a static Mapper.CreateMap, it works fine. Do projections work only with static API? I want to avoid the static API.
Full code:
public class ItemEntityToItemView : Profile
{
public override void Configure()
{
CreateMap<ItemEntity, ItemView>();
// Without this line, I get missing Map type configuration.
Mapper.CreateMap<ItemEntity, ItemView>();
}
}
public interface IEntitiesProjector
{
IQueryable<T> SelectTo<T>(IQueryable source);
}
public class EntitiesProjector : IEntitiesProjector
{
private readonly IMapperConfiguration _mapperConfig;
public EntitiesProject(IMapperConfiguration mapperConfig)
{
_mapperConfig = mapperConfig;
}
public IQueryable<T> SelectTo<T>(IQueryable source)
{
return source.ProjectTo<T>(_mapperConfig);
}
}
public class ItemsRepository : IITemsRepository
{
public IQueryable<ItemEntity> GetById(int id)
{
return _dbSet.Where(x => x.Id == id);
}
}
public class Service
{
private readonly IEntitiesProjector _projector;
public Service(IEntitiesProject entitiesProjector)
{
_projector = entitiesProjector;
}
public List<T> GetItem(int id)
{
IQueryable<ItemEntity> itemsQueryable = ItemsRepository.GetById(id);
return _projector.SelectTo<ItemView>(itemsQueryable);
}
}
My Autofac registration :
builder.RegisterAssemblyTypes().AssignableTo(typeof(Profile)).As<Profile>();
builder.Register(c => new MapperConfiguration(cfg =>
{
cfg.CreateMap<IdentityUser, AspNetUser>().ReverseMap();
})).AsSelf().As<IMapperConfiguration>().SingleInstance();
builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
builder.Register<EntitiesProjector>().As<IEntitiesProjector>().SingleInstance();
The reason is the following block:
public class EntitiesProjector : IEntitiesProjector
{
private readonly IMapperConfiguration _mapperConfig;
public EntitiesProject(IMapperConfiguration mapperConfig)
{
_mapperConfig = mapperConfig;
}
public IQueryable<T> SelectTo<T>(IQueryable source)
{
return source.ProjectTo<T>(_mapperConfig);
}
}
source.ProjectTo is an extension method which has 5 overloads. In documentation they are passing instance of MappingConfiguration class there, and you are passing instance of IMapperConfiguration (interface). You think it will have the same effect, but it does not. IMapperConfiguration interface does not implement IConfigurationProvider interface, and that (IConfigurationProvider) is what correct overload of ProjectTo accepts. But, there is another overload of ProjectTo, which accepts "object parameters". Because it accepts object - it will match anything which did not fit other overloads. So what you are really calling is ProjectTo(object) overload, which has nothing to do with configuration, and your IMapperConfiguration together with profiles and maps is completely ignored.
Quickfix will be
public class EntitiesProjector : IEntitiesProjector
{
private readonly IConfigurationProvider _mapperConfig;
public EntitiesProjector(IMapperConfiguration mapperConfig)
{
_mapperConfig = (IConfigurationProvider)mapperConfig;
}
public IQueryable<T> SelectTo<T>(IQueryable source)
{
return source.ProjectTo<T>(_mapperConfig);
}
}
But of course you should better register your configuration as IConfigurationProvider in your container, that is just quick fix to ensure problem is really here.
As for static Mapper.CreateMap - well it's static, so works regardless of what you pass to ProjectTo.
As a side note this shows you how to not design api. Whenever you have many overloads and one of them accepts generic object and does completely different thing than all other overloads - that is asking for trouble.
I have the following methods on a Entity Framework 6 generic Repository:
public void Add<T>(T entity) where T : class {
_context.Set<T>().Add(entity);
} // Add
public void Add<T>(Expression<Func<T, Boolean>> criteria) where T : class {
_context.Set<T>().AddRange(_context.Set<T>().Where(criteria));
} // Add
public IQueryable<T> Find<T>(Expression<Func<T, Boolean>> criteria) where T : class {
return _context.Set<T>().Where(criteria);
} // Find
How can I make these methods async?
Thank You,
Miguel
I really don't think you should force your repository to be async. What you should do instead is to make async your business logic, that would eventually reference your repositories and access them as needed. Your data access shouldn't know anything about the way it will be used somewhere else.
I have the following fake repository that I use for unit testing. How would I implement the Attach(T entity) method in this repository?
(In my real repository, the Attach(T entity) method is used to attach an object to my Entity Framework 4 data context).
public class FakeRepository<T> : IRepository<T> where T : class, new()
{
private static List<T> entities = new List<T>();
public IQueryable<T> Entities
{
get { return entities.AsQueryable(); }
}
public T New()
{
return new T();
}
public void Create(T entity)
{
entities.Add(entity);
}
public void Delete(T entity)
{
entities.Remove(entity);
}
public void Attach(T entity)
{
//How to implement Attach???
}
public void Save()
{
//Do nothing
}
public void Dispose()
{
return;
}
}
To answer this, you have to ask yourself "what is the purpose of "Attach?" You probably know that the point is to tell the repository "this object is persisted in the database but you aren't currently tracking it; I have made updates to it and I want you to commit them when I tell you to submit your changes."
Thus, to test that Attach is working properly, you should maintain a collection of attached objects and add an entity to this collection when it is passed a parameter to Attach.
So, the simplest implementation would be
entities.Add(entity);
but you could consider something more fine-grained. Note that you need to expose a method that lets you assert that the entity was successfully attached (in EF4 you can use ObjectStateManager.TryGetObjectStateEntry).
get rid of the static word on the entities member. Now just do
enitities.Add(entity)
What is the best approach to implement a CRUD on the BL using interface that will be used to abstract DAL operations? I need your opinion guys..
Here's my draft..
Data Entities that are mapped in the database table
public class Student
{
public string StudentId { get; set; }
public string StudentName { get; set; }
public Course StudentCourse { get; set; }
}
public class Course
{
public string CourseCode { get; set; }
public string CourseDesc { get; set; }
}
I created an CRUD Interface to abstract the object's operations
public interface IMaintanable<T>
{
void Create(T obj);
T Retrieve(string key);
void Update(string key);
void Delete(string key);
}
And then a component that manages the Entity and its operations by implementing the interface
public class StudentManager : IMaintainable<Student>
{
public void Create(Student obj)
{
// inserts record in the DB via DAL
}
public Student Retrieve(string userId)
{
// retrieveds record from the DB via DAL
}
public void Update()
{
// should update the record in the DB
}
public void Delete(string userId)
{
// deletes record from the DB
}
}
sample usage
public void Button_SaveStudent(Event args, object sender)
{
Student student = new Student()
{
StudentId = "1", StudentName = "Cnillincy"
}
new StudentManager().Create(student);
}
as you can see, there is quite an abnormalities on the update method
public void Update()
{
// should update the record in the DB
}
what should this method have to update the objects property? should I inherit the Student?
public class StudentManager : Student , IMaintainable<Student>
{
public void Update()
{
//update record via DAL
}
}
public void Button_SaveStudent(Event args, object sender)
{
Student student = new StudentManager();
student.StudentId = "1";
student.StudentName = "Cnillincy"
student.Update()
}
Or should I just contain the Student class as an attribute of the Student manager?
public class StudentManager : IMaintainable<Student>
{
public Student student { get; private set };
public void Create() {}
public void Update() {}
public void Retrieve() {}
public void Delete() {}
}
Which more appropriate? What about the interface? Any other suggestions guys? thanks..C
Your CRUD interface should probably look like
public interface IMaintanable<T>
{
string Create(T obj);
T Retrieve(string key);
void Update(T obj);
void Delete(string key);
}
that is, both Create and Update take a copy of the object you're updating. The difference is that the Update can get the key from the obj, so it knows which object it's changing. Create would normally cause the key to be created so you pass it back as a return value. Hope that helps.
(The Update might also pass back the key too.)
Personally, I think that all you are missing is the appropriate terminology. What this really is an approximation of a very helpful pattern, called the repository pattern. As far as type-awareness, goes, the implementation would be referred to as a generic repository.
The way I have personally implemented in the past was to have an interface defining the repository, such as IRepository<T>, and a base class that is specific to the type of repository, such as a SqlRepositoryBase<T>. The reason that I would do this is that I can put the implementation-specific code in the base class. So, the plumbing is done and I can worry about domain-specific implementation in the final repository, which would be StudentRepository, a SqlRepository<Student> (or SqlRepository<IStudent> if you define interfaces for your entity).
It seems that you are concerned about how many objects are instansiated, and I can tell you that you are not generating a significant enough drain on resources to really be concerned about implementing in this fashion. Old-timers might cringe at the fact, but we are not trying to optimize for 64k or RAM anymore. ;-) It is more about maintainability, code contracts, etc.
Not to add uneeded complexity up-front, but you also might want to look into the Unit of Work Pattern if you are looking at enlisting multiple entities of different types into atomic transactions.
Here are a couple of good references for these topics:
new Repository().DoMagic()
The Unit of Work Pattern
Two takeaways from this in general (IMHO):
I personally disagree with the assumption that a Repository pattern approach only has usefulness in larger projects; especially the Generic Repository pattern. If you start putting code like this into a reusable library, you will be surprised at how quickly you can start creating an invaluable resource of building blocks.
The biggest plus from this approach is the sheer testability of it; even more so than the reusability. If you are looking to mock out your repositories for any sort of a TDD approach, you can do so with little effort. This will allow you to write richer tests around the usages of the repositories throughout your code.
I saw this from Rob Conery that I really like. It's power is in the flexibility of the arguments you can pass to the methods. Your implimentation isn't robust enough IMO. Check out his MVC starter kit here http://mvcstarter.codeplex.com/ (It's called ISession there).
public interface IMaintainable : IDisposable
{
T Single<T>(Expression<Func<T, bool>> expression) where T : class, new();
System.Linq.IQueryable<T> All<T>() where T : class, new();
void Add<T>(T item) where T : class, new();
void Update<T>(T item) where T : class, new();
void Delete<T>(T item) where T : class, new();
void Delete<T>(Expression<Func<T, bool>> expression) where T : class, new();
void DeleteAll<T>() where T : class, IEntity, new();
void CommitChanges();
}
I wouldn't make StudentManager inherit Student, I would make my Update method stateless like your create method, i.e.
public interface IMaintanable<T>
{
void Create(T obj);
T Retrieve(string key);
void Update(T obj);
void Delete(string key);
}
and
public void Update(T obj)
{
// should update the record in the DB
}
Take a look at the new Entity Framework 4 that was recently released. They are featuring a "code by convention" model that allows you to easily map your business objects directly to the database without having to worry about a DAL.
"The Gu" has a great series outlining how easy it is to map your objects, and even do some simple modifications when linking to the database through the DbContext model it uses.
It is worth noting that the current release is at CTP4, but I anticipate most of the issues have already been worked out with the framework and should serve you well.
I changed the responses here a little bit, to this:
public interface IMaintanable<T>
{
Guid Create(T obj);
T Read(Guid key);
bool Update(T obj);
bool Delete(Guid key);
}
This interface is based on my database structure. I use Guids for primary keys.
I'm currently developing a medium sized application, which will access 2 or more SQL databases, on different sites etc...
I am considering using something similar to this:
http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html
However, I want to use fluent nHibernate, in place of Linq-to-SQL (and of course nHibernate.Linq)
Is this viable?
How would I go about configuring this?
Where would my mapping definitions go etc...?
This application will eventually have many facets - from a WebUI, WCF Library and Windows applications / services.
Also, for example on a "product" table, would I create a "ProductManager" class, that has methods like:
GetProduct, GetAllProducts etc...
Any pointers are greatly received.
In my opinion (and in some other peoples opinion as well), a repository should be an interface that hides data access in an interface that mimics a collection interface. That's why a repository should be an IQueryable and IEnumerable.
public interface IRepository<T> : IQueryable<T>
{
void Add(T entity);
T Get(Guid id);
void Remove(T entity);
}
public class Repository<T> : IQueryable<T>
{
private readonly ISession session;
public Repository(ISession session)
{
session = session;
}
public Type ElementType
{
get { return session.Query<T>().ElementType; }
}
public Expression Expression
{
get { return session.Query<T>().Expression; }
}
public IQueryProvider Provider
{
get { return session.Query<T>().Provider; }
}
public void Add(T entity)
{
session.Save(entity);
}
public T Get(Guid id)
{
return session.Get<T>(id);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return session.Query<T>().GetEnumerator();
}
public void Remove(T entity)
{
session.Delete(entity);
}
}
I do not implement a SubmitChanges like method in the repository itself, because I want to submit the changes of several repositories used by one action of the user at once. I hide the transaction management in a unit of work interface:
public interface IUnitOfWork : IDisposable
{
void Commit();
void RollBack();
}
I use the session of an NHibernate specific unit of work implementation as session for the repositories:
public interface INHiberanteUnitOfWork : IUnitOfWork
{
ISession Session { get; }
}
In a real application, I use a more complicated repository interface with methods for things like pagination, eager loading, specification pattern, access to the other ways of querying used by NHiberante instead of just linq. The linq implementation in the NHibernate trunk works good enough for most of the queries I need to do.
Here are my thoughts on generic repositories:
Advantage of creating a generic repository vs. specific repository for each object?
I have successfully used that pattern with NHibernate, and haven't found any real shortcomings.
The gist is that truly generic repositories are a bit of a red herring, but the same benefits can be realized by thinking about the problem slightly differently.
Hope that helps.