Is it bad to have some common methods in POCO entities?
Is it bad design to have some common functions in POCO entities in Asp.NET MVC 3 + EF CF project? Let's say i need function 开发者_高级运维to get next record code generated by entity properties :
public class Warehouse {
public string ReceivingRecordCodeFormat { get; set; }
public int ReceivingRecordCodeNextNumber { get; set; }
#region functions
public string GetNextReceivingRecordCode()
{
return ...
}
#endregion
}
I suggest to keep POCOs as simple as possible and create service layer for methods like that.
While I agree with maxlego that POCO classes should be as simple as possible, I'm not sure that EF Code First entities should be POCOs.
My practice is to include logic that only affects a single entity in that entity class. Especially if those methods might be called from multiple services (or multiple controllers, if you're using those as your service layer). Otherwise, your services will have to call into other services, which leads to a tight coupling between services and circular reference issues if you're using any kind of IoC container.
Putting the logic right in the entity has the best potential for reuse without having to repeat the code in multiple places.
For logic that involves a collection of entities, I use a service, rather than trying to do it with static methods in the entity class.
I also suggest using POCO view models and not passing your EF entities directly to views, especially if you start adding logic to them.
精彩评论