Reputation: 30478
We have a simple database but which can contain thousands of rows. We're trying to build a simple, lightweight ORM layer over it. Think Dapper. However, we're struggling to figure out how to ensure there is one and only ever one object per ID.
Consider the following data:
ID Last First
===== ========== =======
19 Donnely Rick
20 Donovan Sarah
21 Edwards Sandra
Now consider the following SQL which is used to create Person objects in the ORM layer.
Select * From People Where ID = 20;
Select * From People Where LastName Like 'Don*'
In the first case, you'd get back 'Donovan' but in the second, you'd get back both 'Donovan' and 'Donnely'. Since Donovan had already been returned, we want that instance to come back.
Now of course you would need some lookup by ID. That's easy. What isn't is querying the database, returning rows, then determining that when creating objects you either need to create a new one or update an existing one (in case the data changed.)
The only thing I can think of is having the lookup have a method GetObjectById which either returns an existing object, or creates a new one, stores it, then returns that. I assume it would also have to be based on weak references so they don't just 'hang around' in memory all the time.
// Assume the implementation stores the references weakly
public Person GetPersonById(int id)
{
Person person = this[id]; // assume this returns null if not found
if(person == null)
{
person = new Person(id);
this[id] = person;
}
return person;
}
...or am I going about this all wrong?
Upvotes: 0
Views: 773
Reputation: 56909
One option for this is to use the CSLA framework. It isn't an ORM, it is a "smart object" framework. It has simple, efficient change tracking of entities and collections of descendant entities. It also has several optional features, such as:
The downside is that there is quite a learning curve to learn the framework (although there is good documentation), and it is not very DI or test framework friendly.
Upvotes: 2