LINQ2SQL DataLayer / Repository Suggestion - c#

My current respository is as follows , please suggest , i am currently using LINQ2SQL Data context per insert/delele/update
namespace Lib.Repository
{
public class MotorRenewalDataRepository
{
public MotorRenewalDataRepository()
{
}
public MotorRenewalData GetByID(long id)
{
using(var _context=DatabaseFactory.Create(false))
{
return _context.MotorRenewalDatas.Where(p => p.MotorRenewalDataID == id).FirstOrDefault();
}
}
public MotorRenewalData Insert(MotorRenewalData entity)
{
using (var _context = DatabaseFactory.Create(false))
{
_context.MotorRenewalDatas.InsertOnSubmit(entity);
_context.SubmitChanges();
return entity;
}
}
public void Update(MotorRenewalData entity)
{
using (var _context = DatabaseFactory.Create(true))
{
var dbEntity = _context.MotorRenewalDatas.Where(p => p.MotorRenewalDataID == entity.MotorRenewalDataID)
.FirstOrDefault();
Common.CopyObject<MotorRenewalData>(entity, dbEntity);
_context.SubmitChanges();
}
}
}
}

If I understand your question correctly, you are looking for suggestions on how to properly implement the repository pattern. Here is a good practice of using the repository pattern. First you will want to create an interface for your repository. This is where you define what a repository can do.
public interface IRepository<T>
{
void Add(T entity);
void Delete(T entity);
void Save();
IQueryable<T> FindAll();
}
Next you can create the individual repositories. The first thing you want to do here is to create an interface for anything outside of a normal repository that you might be doing.
public interface IMotorRenewalRepository : IRepository<MotorRenewal>
{
MotorRenewal FindMotorRenewalById(int id);
}
And that interface will implement the IRepository of MotorRenewal so that you get everything from the IRepository and everything you define in IMotorRenewalRepository. The interface is most commonly used when you what to use some sort of dependency injection when writing fake objects and unit tests for your repository.
Now write your MotorRenewalRepository and implement the IMotorRenewalRepository.
public class MotorRenewalRepository : IMotorRenewalRepository
{
MyDataContext _dataContext = new MyDataContext();
public void Add(MotorRenewal motorRenewal)
{
_dataContext.MotorRenewals.InsertOnSubmit(motorRenewal);
}
public void Delete(MotorRenewal motorRenewal)
{
_dataContext.MotorRenewals.DeleteOnSubmit(motorRenewal);
}
public void Save()
{
_dataContext.SubmitChanges();
}
public IQueryable<MotorRenewal> FindAll()
{
return _dataContext.MotorRenewals.AsQueryable();
}
public User FindMotorRenewalById(int id)
{
return _dataContext.MotorRenewals.Where(p => p.MotorRenewalDataID == id).SingleOrDefault();
}
}
This implementation is a lot easier to understand. Notice you do not need an update. An update is really just you pulling a MotorRenewal object out of the repository, editing it, and calling .Save().
You can use a class level variable for your data context rather than creating a new one each time you call a method on your repository. MyDataContext should come from the model you created when dragging in your LinqToSql classes from your data connection.

Related

How to deal with an IDisposable repository with Unity?

I have a job in which I have an IDisposable DbContext. I would like to unit test this job without hitting in a database. What options do i have to do this?
Im using the default Fakes assembly' of microsoft.
My job:
public void Work()
{
do
{
//code here
using (var repository = new Repository<User>())
{
repository.Save(user);
}
} while (true);
}
I'm trying to test and in this part of the test it fails because it actually creates a new instance of the Repository class.
My test Method:
using (ShimsContext.Create())
{
Data.Repository.Fakes.ShimRepository<Domain.Fakes.ShimUser>.Constructor = (a) => { };
Data.Repository.Fakes.ShimRepository<Domain.Fakes.ShimUser>.AllInstances.SaveT0 = (a, b) =>
{
};
var service = GetService();
service.Work(); //Throws exception
}
How can I fake this Save method?
You've violated DIP here, making unit testing your service far more difficult than it should be. You should also avoid generic repositories and favour role interfaces.
Instead, inject an abstraction into your service of your repository, e.g. IUsersRepository which defines your Save method. Then in your unit test of the service you can simply use a stub implementation of IUsersRepository.
Fakes tend to reveal that your code is not properly following the D in SOLID since you are creating dependencies inside your class instead of passing them in.
A much better pattern would to create an ISaveRepository interface that in turn implements IDisposable with an exposed Save() method. You should then inject an instance of your repository into your class. This will allow you to satisfy the using statement testing, as well as implement a mock that defines a .Save() method that does not hit the database.
public class Test
{
private readonly ISaveRepository _userRepository;
public Test(ISaveRepository userRepository)
{
_userRepository = userRepository;
}
public void Work()
{
using (_userRepository)
{
var cont = true;
do
{
_userRepository.Save(new User());
cont = false;
} while (cont);
}
}
}
public interface ISaveRepository : IDisposable
{
void Save<T>(T model);
}
public class Repository<T> : ISaveRepository
{
public void Dispose() { }
public void Save<TT>(TT model) {}
}
public class User {}

Unit Testing With Moq and Repository Pattern

I am new to unit testing and I would like some help. I am using code first with repository pattern. I have a generic repository which contains generic CRUD operation called Generic Repository ( see blow )
public abstract class GenericRepository<T> where T : class
{
private HolidayDatabaseContext _dataContext;
private readonly IDbSet<T> _dbset;
protected GenericRepository(IDbFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
_dbset = DataContext.Set<T>();
}
protected IDbFactory DatabaseFactory
{
get;
private set;
}
protected HolidayDatabaseContext DataContext
{
get { return _dataContext ?? (_dataContext = DatabaseFactory.Get()); }
}
public virtual void Add(T entity)
{
_dbset.Add(entity);
}
public virtual void Update(T entity)
{
_dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
_dbset.Remove(entity);
}
public virtual IEnumerable<T> Enumerable()
{
return _dbset.AsEnumerable<T>();
}
public virtual IQueryable<T> List()
{
return _dbset.AsQueryable<T>();
}
public virtual T GetSingleById(int id)
{
return _dbset.Find(id);
}
public void Save()
{
_dataContext.SaveChanges();
}
}
I have then inherited it into a User Repository and created some specific methods. see below
public class UserRepository : GenericRepository<User>, IUserRepository
{
public UserRepository(IDbFactory databaseFactory)
: base(databaseFactory) { }
public int HolidayEntitlement(int userId)
{
return HolidayEntitlement(userId, DateTime.Now);
}
public int HolidayEntitlement(int userId, DateTime dateTime)
{
//Get the User
var user = this.GetSingleById(userId);
//Work Total Entitlement
int entitlement = user.BaseHolidayEntitlement;
//Years in Service
entitlement += (dateTime - user.EmploymentStartDate).Days / 365;
return entitlement;
}
public int RemainingHolidayEntitlement(int userId)
{
return RemainingHolidayEntitlement(userId, DateTime.Now);
}
public int RemainingHolidayEntitlement(int userId, DateTime dateTime)
{
return int.MinValue;
}
}
I would like to Unit test HolidayEntitlement(int userId, DateTime dateTime) but i need to mock the GetSingleById part in the method
I have written this as a Test but it doesn't compile.
[TestMethod]
public void GetHolidayEntitlement25()
{
//How to write this Unit test
//Setup
var user = new User { AnnualHolidayIncrement = 1, BaseHolidayEntitlement = 25, EmploymentStartDate = new DateTime(2013, 1, 1),Id=1 };
Mock<UserRepository> mock = new Mock<UserRepository>();
mock.Setup(m => m.GetSingleById(1)).Returns(user);
Assert.AreEqual(25, mock.Object.HolidayEntitlement(1));
}
Any help would be appreciated
You seem to be saying that you only want to mock part of the interface. When you start encountering this sort of situation it suggests that you are mixing your concerns and probably doing something wrong somewhere.
In this instance your Repository is doing MUCH more than just CRUD and therefore has multiple responsibilities (it should only have one, lookup SOLID programming). You are performing Business logic in the repository and it should not live there! Anything other than simple CRUD operations should be moved out into the Business Logic Layer. I.e. your HolidayEntitlement method calculates something by applying some logic and is therefore NOT a CRUD / repository operation!
So... What you should do is move the business logic bits out into a new class, say UserLogic. Within the UserLogic class you would use an injected IUserRepository to communicate with your repository. In UserLogic that is where you would put your HolidayEntitlement method and it would make a call to IUserRepository.GetSingleById. So, when you then test your UserLogic class you would inject in your mock IUserRepository that would have the stub version of GetSingleById and then you will be back on the right track!
I hope that makes sense / helps?!
--ORIGINAL POST--
P.S. My original post stated that you should mock interfaces, not instances so this still applies and I will leave here for reference:
You should be mocking IUserRepository NOT UserRepository.
That is because UserRepository is an implementation of IUserRepository. You want to say that you are giving it a NEW implementation, i.e. your mock. At the moment you are using the ACTUAL class UserRepository.
Mocking is generally used when you need to supply a fake dependency and in this case you appear to be trying to Mock the System Under Test (SUT) which doesn't really make sense - there's literally no point because your test is not actually telling you anything about the behaviour of UserRepository; all you are doing is testing if you setup your Mock correctly which isn't very useful!
The test code you have given seems to indicate that you want to test UserRepository.HolidayEntitlement.
I would be much more inclined to move functions like that out of your Repository class and into a separate business-logic type class. This way you can test the logic of calculating a user's holiday entitlement in total isolation which is a major principle of unit testing.
In order to test that this function does what it's supposed to do (i.e perform a calculation based on properties of a User) you need to ensure that whatever User instance is being operated on within that function is 100% isolated and under your control - either with a Mock or Fake (Stub) instance of User, in this case Mocks are an excellent choice because you only need to implement the parts of the dependency that your SUT is going to need.
So, what you could do is this:
Define an interface for User
public interface IUser
{
int BaseHolidayEntitlement{get;set;}
DateTime EmploymentStartDate {get;set;}
//other properties for a User here
}
Implement this on your User class
public class User:IUser
{
//implemement your properties here
public int BaseHolidayEntitlement{get;set;}
public DateTime EmploymentStartDate {get;set;}
//and so on
}
Create a class for User logic
public class UserRules
{
public int GetHolidayEntitlement(IUser user,DateTime dateTime)
{
//perform your logic here and return the result
}
}
Now your test becomes much simpler and doesn't even need the repository
[TestMethod]
public void GetHolidayEntitlement_WithBase25_Returns25()
{
//Arrange
var user = new Mock<IUser>();
//setup known, controlled property values on the mock:
user.SetupGet(u=>u.BaseHolidayEntitlement).Returns(25);
user.SetupGet(u=>u.EmploymentStartDate).Returns(new DateTime(2013,1,1));
var sut = new UserRules();
int expected = 25;
//Act
int actual = sut.GetHolidayEntitlement(user.Object,DateTime.UtcNow);
//Assert
Assert.AreEqual(expected,actual,"GetHolidayEntitlement isn't working right...");
}

C# generic repository used for unit testing

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)

Implementing a CRUD using an Interface

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.

Using a Generic Repository pattern with fluent nHibernate

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.

Categories

Resources