views:

32

answers:

2

Could anyone tell me where is the best place to put my business methods when using EF4 code first POCOs? Should they go in the POCO class? E.g.

public class customer
    public property Id as int32
    public property Name as string
    public property Archived as boolean

    public sub MarkAsArchived
       me.Archived = true 
    end sub

    public function EmailAllInvoices as boolean
        ...
    end function
end class

Or should the POCO class be as clean as possible and a seperate class be used for business logic which accepts an instance of a customer POCO in the constructor to work on?

Thanks.

A: 

That is definitely dependent on "architecture" of your business layer. You can use POCO as data transfer object and have some upper level business layer class which will handle business operations - basically we can talk about Transaction script pattern. Or you can place methods to your POCO objects and "promote" them to Domain objects. Then your business logic will be inside your domain objects and domain services (some business logic functionality is for several domain objects so it should be placed to separate class). This is called Domain driven design (but it suggests much more architecture related ideas).

Ladislav Mrnka
+1  A: 

@Ladislav Mrnka is right, it depends on your architecture.

How complex are your business rules? Are they likely to change often? What clients will consume your Model, just your own Web Site, or are you exposing API's, OData, etc?

All questions that need to be answered.

Personally, we have simple business rules, and a fairly straightforward architecture.

Therefore, i do all validation in a service layer, and i create partial classes for my POCO's to faciliate the business rules, and throw Custom Exceptions.

E.g

public void Add(Order order)
{
   try
   {
      order.Validate(); // method in Order.cs partial class
      repository.Add(order);
   }
   catch (InvalidOrderOperationException exc) // custom exc
   {
      // do something
   }
}

As i said - depends on your architecture.

If you have very complicated business rules, consider using the Specification pattern.

The "DDD-God" (Martin Fowler) has a good write-up on it here.

RPM1984
I was hoping for an all-in-one implementation that could be used across all of our projects, small and large.
Jamie Carruthers
@Jamie Carruthers - it's not that simple, you must have some idea on the overall architecture. What "projects" will it be shared across, how do you wish to publish this to those projects, via a compiled DLL, or are you going to expose operations via WCF, Web API? The issue here is the POCO's (if you want to use WCF, you need self-tracking entities). We really need more information about what the projects are.
RPM1984