I'm working with EF 4.1 Database first. I was wondering what sort of things I may use Entity Partial Classes for. What would some examples of possible functionality I might want to add to partial classes. I'm just trying to understand if I should make my entities more capable or if I should be looking to add the functionality elsewhere? Are there good cases for things I may want to add to my entities?
For example I have an entity that has various child properties with start and end dates. These dates must not overlap. Is that something I should enforce on the parent entity?
Ok so suggestions seem to be开发者_如何转开发 validation and business logic. Additionally calculating things so that DB the doesn't have computed columns.
Should I be tying business logic to entity framework entities? What if I wanted to move away from EF?
Thanks
Graeme
Validatable Objects and MetadataType attributes are used in the partial classes by frameworks such as MVC, for example.
Here's an example of using the MetadataType attribute:
[MetadataType(typeof(UserMetadata))]
public partial class User
{
private class UserMetadata
{
[DisplayName("User Id")]
public long UserId
{
get;
set;
}
[DisplayName("User Name")]
public string UserName
{
get;
set;
}
}
}
When you use the MVC framework, any model that has these attributes will be read for purposes of automatic generation of label fields for the corresponding displays/editors.
Example of using IValidatableObject
public partial class Apple : IValidatableObject // Assume the Apple class has an IList<Color> property called AvailableColors
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
foreach (var color in this.AvailableColors)
{
if (color.Name == "Blue") // No blue apples, ever!
{
yield return new ValidationResult("You cannot have blue apples.");
}
}
}
}
MVC will pick up on this IValidatableObject and ensure that any Apple that comes its way through it's validation step will never come in blue.
EDIT
As an example of your date range concern using IValidatableObject:
public partial class ObjectWithAStartAndEndDate : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.StartDate >= this.EndDate)
{
yield return new ValidationResult("Start and End dates cannot overlap.");
}
}
}
I have used it to augment my generated classes with calculated values, when I'd rather not have the DB have calculated columns.
精彩评论