I don't know about you, but I'm really lazy with bustin' some SQL madness, data mapper tests are a pain, nhibernate .hbm.xml files are a pain!!!
What can a simple developer do to quickly build up a data access layer, and still look pimp?
I came across ActiveRecord by CastleProjects a couple of months ago. It is using ofcourse the active record pattern shown on that Fowler book about enterprise patterns. It uses nhibernate libraries without the pain of creating those damn hibernate files. It just uses System.Attribute
Below is a sample code that I did up just to see how fast it was for me to create a dataaccess layer:
ofcourse we have to start with a Test...
using cargo.domain;
using MbUnit.Framework;
namespace cargo.test
{
[TestFixture]
public class UserTest_DataAccess
{
[Test]
public void ShouldHandleActiveRecordFunctionality()
{
Company company = DomainObjectFactory.CreateTestCompany();
company.Save();
User user = new User();
user.UserName = "jonas";
user.Password = "test";
user.Company = company;
user.Save();
AssertUser(User.FindBy(user.UserName), user);
user.UserName = "updated";
user.Password = "updated2";
user.Update();
AssertUser(User.FindBy(user.Id), user);
user.Delete();
Assert.IsNotNull(Company.FindBy(company.Id));
company.Delete();
Assert.IsNull(Company.FindBy(company.Id));
Assert.AreEqual(0, User.FindAll().Length);
}
private static void AssertUser(User result, User user)
{
Assert.AreEqual(result.UserName, user.UserName);
Assert.AreEqual(result.Password, user.Password);
}
}
}
and now the code....
using Castle.ActiveRecord;
using NHibernate.Expression;
namespace cargo.domain
{
[ActiveRecord("CARGO_USER")]
public class User : ActiveRecordBase<User>, IUser
{
private int id;
private string userName;
private string password;
private int status;
private Company company;
public User()
{
ActiveRecordInitializer.Initialize(GetType().Assembly);
}
public static User FindBy(string userName, string password)
{
return FindOne(Expression.Eq("UserName", userName), Expression.Eq("Password", password));
}
public static User FindBy(string userName)
{
return FindOne(Expression.Eq("UserName", userName));
}
public static User FindBy(int id)
{
return FindOne(Expression.Eq("Id", id));
}
[PrimaryKey(PrimaryKeyType.Native, "user_id")]
public int Id
{
get { return id; }
set { id = value; }
}
[Property("user_name")]
public string UserName
{
get { return userName; }
set { userName = value; }
}
[Property("user_password")]
public string Password
{
get { return password; }
set { password = value; }
}
[Property("user_status")]
public int Status
{
get { return status; }
set { status = value; }
}
[BelongsTo("COMPANY_ID")]
public Company Company
{
get { return company; }
set { company = value; }
}
}
}

0 comments:
Post a Comment