开发者

How do I implement Business Logic on auto generated entities in Microsoft MVC2?

I'm new to MVC and I'm trying to开发者_StackOverflow figure out how to implement business logic in the auto generated Entities in an MVC project.

I know that if I create my own Model class I can put [Required] and other attributes on the fields but there doesn't seem to be an option to do that in the .edmx file.

Is there something I'm missing here?

Should I be creating my own classes that use the entities and put the logic in there? It seems like there should be a way for me to do less work.

Thanks!


This can be achieved by using the buddy-class functionality in .NET implemented specifically for this reason. Once you have created your entities in your .ebmx file you can create partial classes to accompany your entities which define your business rules in a 'buddy class'.

[MetadataType(typeof(ProductMetadata))]
public partial class Product {

    internal sealed class ProductMetadata {
        [DisplayName("Name")]
        [Required]
        public string Name { get; set; }

        [DispayName("Price")]
        [Required, Range(1,10000)]
        public decimal Price { get; set; }

        [DisplayName("Description")]
        public string Description { get; set; }
    }
}

In the example above, assume that you already have a "Product" type defined in your object context which has properties for "Name", "Price", and "Description". So long as the buddy class type referenced by the MetadataTypeAttribute has matching property names, the attributes applied to the properties in the buddy class will be applied to the implementation type.

Note: if there are any property names in the buddy class which do not match the implementation type, you will get a runtime error. You only need to create matching properties in the buddy class for the properties you are interested in applying business rules to; all properties are optional.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜