Monday, July 5, 2010

Data Access Application Block 5.0 – Part 3

Updating data
The Data Access block provides features that support data updates. You can execute update queries (such as INSERT, DELETE, and UPDATE statements) directly against a database using the ExecuteNonQuery method. The ExecuteNonQuery method has a broad set of overloads. You can specify a CommandType (the default is StoredProcedure) and either a SQL statement or a stored procedure name. You can also pass in an array of Object instances that represent the parameters for the query.
The data accessor instance passed as parameter to the update method in the repository class methods are later used to construct the updated entity object. The code sample is as
public class CustomerUpdateAccessorFactory : ISaveAccessorFactory<Customer, long, CustomerUpdateIdentity>
{
    public DataAccessor<CustomerUpdateIdentity> ConstructDataAccessor(Database database)
    {
        return database.CreateSprocAccessor<CustomerUpdateIdentity>("usp_UpdateCustomer", new UpdateCustomerParameterMapper(), ConstructMapper());
    }

    public IRowMapper<CustomerUpdateIdentity> ConstructMapper()
    {
        IRowMapper<CustomerUpdateIdentity> rowMapper = MapBuilder<CustomerUpdateIdentity>.MapAllProperties()
            .Map(x => x.Version).WithFunc(dataRecord =>
            {
                int index = dataRecord.GetOrdinal("VersionNew");
                if (!dataRecord.IsDBNull(index))
                {

                    byte[] version = new Byte[(dataRecord.GetBytes(index, 0, null, 0, int.MaxValue))];
                    dataRecord.GetBytes(index, 0, version, 0, version.Length);
                    return version;
                }
                return null;
            })
            .Build();
        return rowMapper;
    }

    public object[] LoadParameters(Customer entity)
    {
        return new object[] { entity.Id, entity.FirstName, entity.LastName, entity.Address, entity.Version };
    }
}

The repository method for update
public TIdentity Save(ISaveAccessorFactory saveAccessorFactory, T entity)
{
    return saveAccessorFactory.ConstructDataAccessor(___Database)
        .Execute(saveAccessorFactory.LoadParameters(entity))
        .FirstOrDefault();
}

[TestMethod]
public void Can_updated_values_into_db()
{
    var baseRepository = new BaseRepository<Customer, long>();
    Customer existingCustomer = baseRepository.FindOne<long>(new GetCustomerAccessor(), 288);
    var customerUpdateIdentity = baseRepository.Save<CustomerUpdateIdentity>(new CustomerUpdateAccessorFactory(), existingCustomer);
    Assert.IsNotNull(customerUpdateIdentity.ChangedDate);
    Assert.IsNotNull(customerUpdateIdentity.Version);
}

1 comment:

Chandra Kumar said...

Prajeesh need complete code . Please give your complete code as a download option as well.

Your current code gives partial information.Makes me keep guessing.