C# – Good design pattern for linq to sql

cdesign-patternslinq

I currently have a linq to sql project that was used for one project and not much work was put into it, only the generated context and entities were used. Since then the project has started to become referenced in other projects and is growing rather quickly. My concern at first was duplicate code, for example:

using (DataContext dc = new DataContext())
{
    User myUser = dc.Users.Where(u => u.UserId == 1).SingleOrDefault();
}

This could be used in my project, but also used in someone else's project. I don't want smelly projects…

Lately we have started implementing the repository design so we even have a single repository that can handle multiple entities, so now queries go to the repository rather than the data context directly.

We have implemented a generic repository with methods like All() and FindAll() etc… but my question is when we come to doing more complex things like creating a record that involves creating numerous different entities, does this go into the repository layer or do I need to start looking at another design pattern?

Best Answer

A Save() method for a complex object would go into your Repository pattern interface. No, you don't necessarily need to use a different pattern.

A Repository should ideally abstract away all underlying storage (i.e. DB, memory collection, XML file etc) implementation detail from the object model that it works with. So if you are creating a complex object which has relationships between different entities, model this as a set of classes and write a method on your Repository to accept that type and do the dirty work of creating the classes in your physical storage device (whatever that may be).