repository pattern linq to sql (stored procedure) - repository

i am looking for repository pattern sample that i can learn from it and i have read lot of blogs and seems like everyone has their own opinions towards -implementing repository pattern-
any help?
Thanks,

Here it's

The repository pattern and Linq to Sql won't match. Sorry.
IMHO, pretty much all I-hide-data-storage-from-u patterns are broken in one way or another. Either you have leaky abstractions or they require LOTS of redundant code.
Imagine this... You have an IRepository which uses Linq to Sql to generate a Foo type that matches a Foo database table. Awesome! Everything worked out better than I expected.
Except the Foo table is linked to the Bar table. So now when you return all Foos via the IRepository interface for Foo, you have to keep your DataContext alive so that if somebody goes foreach(var bar in Foo.Bars) they'll get what they expect.
But how do you manage that DataContext? Do you keep one for all instances of IRepository or one per instance? What happens when a Bar is created, a new Foo is added to it, and saved to the IRepository? You've added a Foo without the Foo repository! And it gets worse, with side effects from not using the L2S pattern correctly come creeping out of your IRepository.
So you try to scope your L2S types within your IRepository implementations, duplicating all your data within new types that you coded by hand. But then how do you handle one-to-many and many-to-many relationships? Load it all into memory, or load a piece by piece, ensuring you lose any way to make efficient queries to the database?
The whole frigging thing is depressing. It would be wonderful to be able to hide the fact that you're not actually storing your data in a database, but unless you're lucky (i.e., your design is simple), you're not going to be able to get away with it.

Related

NHibernate and repositories design pattern

I've been working with NHibernate for quite a while and have come to realize that my architecture might be a bit...dated. This is for an NHibernate library that is living behind several apps that are related to each other.
First off, I have a DomainEntity base class with an ID and an EntityID (which is a guid that I use when I expose an item to the web or through an API, instead of the internal integer id - I think I had a reason for it at one point, but I'm not sure it's really valid now). I have a Repository base class where T inherits from DomainEntity that provides a set of generalized search methods. The inheritors of DomainEntity may also implement several interfaces that track things like created date, created by, etc., that are largely a log for the most recent changes to the object. I'm not fond of using a repository pattern for this, but it wraps the logic of setting those values when an object is saved (provided that object is saved through the repository and not saved as part of saving something else).
I would like to rid myself of the repositories. They don't make me happy and really seem like clutter these days, especially now that I'm not querying with hql and now that I can use extension methods on the Session object. But how do I hook up this sort of functionality cleanly? Let's assume for the purposes of discussion that I have something like structuremap set up and capable of returning an object that exposes context information (current user and the like), what would be a good flexible way of providing this functionality outside of the repository structure? Bonus points if this can be hooked up along with a convention-based mapping setup (I'm looking into replacing the XML files as well).
If you dislike the fact that repositories can become bloated over time then you may want to use something like Query Objects.
The basic idea is that you break down a single query into an individual object that you can then apply it to the database.
Some example implementation links here.

best practice for a function which interacts with a database

Say I have a User object, which is generated by a Usermapper. The User object does not know anything about the database/repository in use (which I believe to be good design).
When creating a User, I only want it to have it filled by the mapper with the most trivial things e.g. Name, address etc. However after object instantiation I might have a method userX.getTotalDebt(), getTotalDebt() would need to reconnect to the database , because I don't want this relatively expensive operation to be done for every User instantiation (multiple tables needed etc). If I'd simply insert some sql in the getTotalDebt() or a dependency back to the Mapper where the coupledness is growing tight very fast.
There is an obvious good/best practice for this, because it's a situation arises often, however I can't find it or I'm looking at this problem totally from a wrong angle.
Say I have a User object, which is generated by a Usermapper. The User object does not know anything about the database/repository in use (which I believe to be good design).
They are often referred to as POCOs (Plain Old CLR Objects).
When creating a User I only want it to have it filled by the mapper with the most trivial things e.g. Name, address etc.
There are several OR/M layers which can achieve this. Use either nhibernate or Entity Framework 4.1 Code First.
I might have a method userX.getTotalDebt(), getTotalDebt() would need to reconnect to the database
Then it's not a poco anymore. Although it is possible using a transparent proxy. Both EF and nhibernate supports this and it's called Lazy Loading.
There is an obvious good/best practice for this, because it's a situation arises often, however I can't find it or I'm looking at this problem totally from a wrong angle
I usually keep my objects dumb and disconnected. I use the Repository pattern (even if I use nhibernate or another orm) since it makes my classes testable.
I either use the repository classes directly or create a service class which contains all logic. It depends on how complex my application is.

Which is a better design?

I have a team leader object, and have lot of team members object own by team leader.
Both team leader and team members have a function called "writeDB".
So, design 1:
Have a common writeDB function in DBUtility:
teamLeader.writeDB(); //calling DBUtility like this DBUtility.insert(self);
teamMember.writeDB(); //calling DBUtility like this DBUtility.insert(self);
design 2:
Both implementing a writeDB Interface:
teamLeader.writeDB(); //implement the write DB itself;
teamMember.writeDB(); //implement the write DB itself;
design 1 can centralize the writingDB logic into one single class, if there is any problems in writing DB, I only need to change the DBUtility class, also, if I would like change the DB, I only need to change one place.
design 2 can separate the code into two places. If one developer coding about teamLeader logic, he don't need to update the DBUtility, also, if the code move to somewhere else, he don't need to copy the useless function, for example, the DBUtility's teamMember writeDB function is not needed.
What do you think for better maintain? or the design 3 from you. Thank you.
Putting aside my concern that any model level class would have an explicit public method called writeDB, I would go for option 1
Persistence should be considered orthogonal to the core responsibilities of these classes.
The benefit comes in several parts
Cleanly separating the responsibilities will result in a more
object-oriented design. More object-oriented means more comprehensible and easier to manage over time.
In larger teams, you may well have a sub-group working explicitly on the persistence layer and they can have total responsibility for managing and optimising the code.
When you inevitably release that database X is better than database Y (or indeed that SQL is a bad idea), the persistence logic is not scattered across the code base
That pesky writeDB() method
Just to go back to my first point, you shouldn't have a public method called writeDB. You also probably don't want a more generic name such as save. The better design would allow the classes themselves to decide when they need to be persisted
Why do TeamMember and TeamLeader have to know about the database at all? I think this would be better:
DBUtility.write( teamMember );
DBUtility.write( teamLeader );
Better still is if DBUtility is not static, allowing you to see what it really depends on. Static is the same as global. Global puts an assumption in place about only ever doing it one way, and this generally causes problems later.
DBUtility dbUtility = new DBUtility( dbConnection );
dbUtility.write( teamMember );
dbUtility.write( teamLeader );
Then later, you might need to write to disk as XML. You should be able to add this feature without changing your TeamLeader and TeamMember.
XMLUtility xmlUtility = new XMLUtility( stream );
xmlUtility.write( teamMember );
xmlUtility.write( teamLeader );
I prefer to use the second design because it is more object oriented and you will benefit from separating the code.
I should go with design 2 which will force all my classes to have writeDB method, and I will use design1 to provide this functionality.
This way I will have interface for my objects Leader/Member and will have the actions grouped under on class which knows how to do the actions.
It depends. From a Separation-Of-Concerns principle this shouldn't be in the class itself, but having a class which knows about all others violates the Open-Close-Principle.
There is a third option for this kind of operation (e.g. write to DB), that is to use some metadata in the class and then some code which does write the object to the database by using the metadata information.
The second option is definatly mor OO. Eache type implements the writeDB interface.
If it makes sence when writing teamLeader to also write each teamMember then writeDB implomentation for teamLeader can call writeDB on each teamMember.
That would be the most OO solution.
Howerver, this dosen't take into account persistense layer limitations and efficencies.

What is the interaction between Objective-C and RDBMSes like SQLite?

I would like to learn how to persist data to a RDBMS from Objective-C, and I don't really know where to start to learn this. Do I learn a RDBMS? Do I learn data modeling?
I'm wondering are there techniques or special considerations when modeling the data as to not run into any pitfalls? I.e. are there rules of thumb like "don't subclass" or "always encapsulate your attributes."
In my limited experience it has been quite difficult to translate an Objective-C class into a relational database. It would seem that CoreData might get me started off on the right path, but it also seems like CoreData kinda just gives me a lot of things to take for granted (I'm curious to know what's going on under the hood with the SQL calls...). Or am I understanding this framework wrong?
I'm looking for any resources that would get me started down the path of better understanding RDBMSes and how Objective-C model classes typically interact with them for data storage.
EDIT:
In an effort to answer my own curiosity, I've picked up Joe Celko's SQL for Smarties as well as Beginning Database Design by Clare Churcher. Neither of them really give much by way of the interaction between controller classes written in non-SQL languages (in my case Objective-C), SQL, and the database. There's a missing link that I'm just not understanding...
Check out BaseTen https://bitbucket.org/mka/baseten/wiki/Home
Sorry it's taken so long to come back to you. What you are asking is not specific to Objective-C. My first introduction of connecting Object-oriented code to RDBMS was Enterprise Object Frameworks in NextStep. But since then, that idea has been copied in most object-oriented languages including Java and Ruby (see ActiveRecord).
Conceptually, on the programming side there is usually a entity class that is used to represent each row of a table. In some cases, such as CoreData or WebObjects, a map is used to create an interface between the application code and the database. Because of this map, a developer can use instances of the generic entity class to represent the data. Of course, many times that class is subclassed to added methods specific to a particular entity.
For example, say you have a table for contacts, which has a column for first name and a column for last name. Often in an application you want to display the full name. In a subclass of the entity class, one can add a method that returns the first and last name as a single string.
In other frameworks, such as ActiveRecord, I believe you must always have a subclass that represents each table.
Conceptually, I find Object-Oriented programming to align well with RDBMS.
Table (contacts) -> Class (Contact)
Row -> Instance of class (aContact)
Columns (firstName) -> Properties (aka instance variables, attributes) (firstName)
Relationships:
to-one (father) -> Properties (father, an instance of Contact)
to-many (emailAddresses) -> Array (emailAddresses, an array of instances of EmailAddress class)
Hope this answers your question better,

DDD: Should everything fit into either Entity or Value Object?

I'm trying to follow DDD, or a least my limited understanding of it.
I'm having trouble fitting a few things into the DDD boxes though.
An example: I have a User Entity. This user Entity has a reference to a UserPreferencesInfo object - this is just a class which contains a bunch of properties regarding user preferences. These properties are fairly unrelated, other than the fact that they are all user preferences (unlike say an Address VO, where all the properties form a meaningful whole).
Question is - what is this UserPreferencesInfo object?
1) Obviously it's not an Entity (I'm just storing it as 'component' in fluent nhibernate speak (i.e. in the same DB table as the User entity).
2) VO? I understand that Value Object are supposed to be Immutable (so you cant cange them, just new them up). This makes complete sense when the object is an address for instance (the address properties form a meaningful 'whole'). But in the case of UserPreferencesInfo I don't think it makes sense. There could be 100 properties (Realistically) There could be maybe 20 properties on this object - why would I want to discard an recreate the object whenever I needed to change one property?
I feel like I need to break the rules here to get what I need, but I don't really like the idea of that (it's a slippery slope!). Am I missing something here?
Thanks
Answer 1 (the practical one)
I'm a huge proponent of DDD, but don't force it. You've already recognised that immutable VOs add more work than is required. DDD is designed to harness complexity, but in this case there is very little complexity to manage.
I would simply treat UserPreferencesInfo as an Entity, and reference it from the User aggregate. Whether you store it as a Component or in a separate table is your choice.
IMHO, the whole Entity vs VO debate can be rendered moot. It's highly unlikely that in 6 months time, another developer will look at your code and say "WTF! He's not using immutable VOs! What the heck was he thinking!!".
Answer 2 (the DDD purist)
Is UserPreferencesInfo actually part of the business domain? Others have mentioned disecting this object. But if you stick to pure DDD, you might need to determine which preferences belong to which Bounded Context.
This in turn could lead to adding Service Layers, and before you know it, you've over-engineered the solution for a very simple problem...
Here's my two cents. Short answer: UserPreferenceInfo is a value object because it describes the characteristics of an object. It's not an entity because there's no need to track an object instance over time.
Longer answer: an object with 100+ properties which are not related is not very DDD-ish. Try to group related properties together to form new VOs or you might discover new entities as well.
Another DDD smell is to have a lot of set properties in the first place. Try to find the essence of the action instead of only setting the value. Example:
// not ddd
employee.Salary = newSalary;
// more ddd
employee.GiveRaise(newSalary);
On the other hand you may very well have legitimate reasons to have a bunch of properties that are no more than getters and setters. But then there's probably simpler methods than DDD to solve the problem. There's nothing wrong with taking the best patterns and ideas from DDD but relax a little of all the "rules", especially for simpler domains.
I'd say a UserPreferenceInfo is actually a part of the User aggregate root. It should be the responsibility of the UserRepository to persist the User Aggregate Root.
Value objects only need to be newed up (in your object model) when their values are shared. A sample scenario for that would be if you check for a similar UserPreferenceInfo and associate the User with that instead of Inserting a new one everytime. Sharing Value Objects make sense if value object tables would get to large and raise speed/storage concerns. The price for sharing is paid on Insert.
It is reasonable to abstract this procedure in the DAL.
If you are not shraing value objects, there is nothing against updating.
As far as I understand, UserPreferenceInfo is a part of User entity. Ergo User entity is an Aggregate root which is retrieved or saved using UserRepository as a whole, along with UserPreferenceInfo and other objects.
Personally, I think that UserPreferenceInfo is entity type, since it has identity - it can be changed, saved and retrieved from repository and still be regarded as the same object (i.e. has identity). But it depends on your usage of it.
It doesn't matter IMHO how object is represented in the DAL - is it stored in a separate table or part of other table. One of the benefits of DDD is persistence ignorance and is ususally a good thing.
Of course, I may be wrong, I am new to DDD too.
Question is - what is this UserPreferencesInfo object?
I don't know how this case is supported by NHibernate, but some ORMs support special concepts for them. For example DataObjects.Net include Structures concept. It seems that you need something like this in NH.
First time ever posting on a blog. Hope I do it right.
Anyway, since you haven't showed us the UserPreferencesInfo object, I am not sure how it's constructed such that you can have a variable number of things in it.
If it were me, I'd make a single class called UserPreference, with id, userid, key, value, displaytype, and whatever other fields you may need in it. This is an entity. it has an id and is tied to a certain user.
Then in your user entity (the root I am assuming), have an ISet.
100 properties sounds like a lot.
Try breaking UserPreferenceInfo up into smaller (more cohesive) types, which likely/hopefully are manageable as VOs.