How/Where to apply business rules to POCO objects?
Let's say I have a POCO with the following:
[DataMember]
public Nullable<int> MetricId
{
get { return _metricId; }
set
{
if (_metricId != value)
{
_metricId = value;
OnPropertyChanged("MetricId");
}
}
}
private Nullable<int> _metricId;
I want to validate that the MetricId
is strictly greater than 0
Obivously, if I put this rule as a data annotation in this class it will be overwritten the next time I regen the poco. Where do I put this lo开发者_Go百科gic?
Thanks!
I seem to remember the suggestion being to utilize partial classes and roll a partial class that implemented the logic you didn't want to be overwritten.
After reading the comments and responses, it seems that creating another class is fine, but by making it partial, it ties my business logic directly to the Entity Framework and the generated POCO code. This is worrisome because as EF4 changes into EF5 and the T4 template changes to the T5 template what will happen to my code? Plus I just don't feel comfortable using partial classes as normal classes.
Instead, and someone can still provide a better answer (please do), I think creating a framework independent object (one not tied to EF) is better. Then I can map it to a generic business object. Something like:
static Customer Map(CustomerPOCO poco)
{
return new Customer
{
CustomerId = poco.CustomerId
...
...
};
}
It's not clean using partial classes lets say you have product abstract lass and derived classes online product and store product. Both inherit price property but price is different. And let's say business logic may be different too. Now you got two additional classes that you don't really need. In larger system, it multiplies.
精彩评论