views:

26

answers:

2

Hi there, I'm in the process of rewriting our application. We are building DataMappers to work in our DAL. My question relates to the situation where I have a complex object from the BLL that get's passed to the DataMapper to be persisted.

Let's say this object has a lot's of properties including lists of other objects.

i.e...

public class Customer
{
    public String name;
    public String age;
    public String ShoeSize;
    public List<Address> a;
    public List<Orders> o;
{

In a situation where maybe "age" was the only field that was updated in the BLL.

What's a good practice for persisting this to the database?

Would you persist the entire structure? or How can I structure this so that my DataMapper would know which fields changed so that I didn't have to update the entire structure in the database? I guess I could have some kind of IsDirty field for each property, but that could get messy really quick.

Thanks,

MW

+1  A: 

If you keep the original object in memory and pass in a new "version" with the changes, you could check the new object for changes and only save that.

public class CustomerMapper {
    // ...
    public void Update(Customer original, Customer update)
    {
        // check each property for changes
    }
    // ...
}

After the update you replace the original object with the new. But be aware of concurrency issues if you have multiple threads.

Paw Baltzersen
Thanks. This may work. I just need to look at handling those concurrency issues.
Michael Wilson
Or just fetch the original from the database and compare it with the modified one before saving changes..
jgauffin
@jgauffin That would work too but requires an extra trip to the DB. Depends on the system and setup.
Paw Baltzersen
A: 

Why reinvent the wheel? I've done a couple of data layers and it's not worth the hassle. All those issues (and a lot that you havent thought of) have already been taken care of when using an existing ORM.

My favorite is nhibernate. It can either give you a lot of power or fix everything with almost zero configuration.

Look here:

jgauffin
Thanks. That would be nice if I could use one on this project.
Michael Wilson
Why not? You're rewriting the application. =) You existing fat objects should work fine with nhibernate as long as the lists/collections implements IList or Set. In other words, you should only have to use nhibernate instead of your current datamapper (which you are building). Not that many changes to the calling code.
jgauffin