Polymorphism: Is ORM entity a Domain Entity or Data Entity?

  1. I’m not entirely sure what you are asking regarding LINQ to SQL, but it’s certainly not the wrong approach to manually create you domain objects. You won’t get properly encapsulated domain objects if you rely on them being code generated.
  2. You have got yourself in a muddle regarding the factory pattern. As mouters has pointed out, you have two objects representing the same thing:

    RepositoryLayer.BankAccount

    DomainObjectsForBank.IBankAccount

Factories are only required when a ‘strategy’ is required for object creation. A classic case for their use is polymorphism & inheritance. Your account class has sub classes, so there is a case for an AccountFactory. But where you have over complicated the situation is by having the repository return some kind of account data object, then passing this to the factory to convert it to the correct sub classed domain object. Instead, the repository should get the data from the database, pass it to the factory, and then return the created domain object from the factory. For example:

public class AccountRepository : IAccountRepository
{
    public Account GetById(Guid id)
    {
        using (AccountContext ctx = new AccountContext())
        {
            var data = (from a in ctx.Accounts
                               where a.AccountId == id
                               select new { AccountId = a.AccountId, CustomerId = a.CustomerId, Balance = a.Balance, AccountType = (AccountType)a.AccountTypeId }).First();


            return _accountFactory.Create(data.AccountId, data.CustomerId, data.Balance, data.AccountType);
        }
    }

}

UPDATE:

My Advice regarding LINQ to SQL is:

  1. Move to Entity Framework if you can as it’s more advanced and is better supported now.
  2. Don’t use it’s generated objects as your domain objects. If you look at the code above, I query the data from my ctx.Accounts and use it to instantiate my domain objects. In my experience trying to use and ORM to build domain objects is problematic: see Rich domain model with behaviours and ORM

Leave a Comment