开发者

MVC 3 - Entity Framework - Scaffolding - Validation issue

开发者 https://www.devze.com 2023-03-23 02:04 出处:网络
Im developing an MVC 3 application with Entity Framework and Im tring to use Scaffolding. To solve \"Type not mappedd issue\" I\'ve done the procedure found here. Everything now works fine.

Im developing an MVC 3 application with Entity Framework and Im tring to use Scaffolding.

To solve "Type not mappedd issue" I've done the procedure found here. Everything now works fine.

Default validation is not working, required field are firing an exception instead of write something on ValidationSummary, so I want to add my custom validations using attributes. The problem is that the solution about "type not mapped issue" has added 2 .tt files and a .cs file for each of my entities, these files are recreated each time my model (.edmx) is changed and saved so I cant put my Data Annotation Validator Attributes in those classes and either I cant create a new partial class with some properties because thay are already defined.

How can I do? May I have to move validation client-side using jquery? Or maybe there a workaround to add Data Annotation Validator Attributes to my entities, I prefer this way to have more visibility of my validations.

开发者_如何学运维

Thanks in advance


I've not used the DbContext generator, but have had similar issues with the POCO Generator. Assuming that the solution is similar:

Modify the T4 template that creates the entity classes to add an extra attribute to the class:

[MetadataType(typeof(CustomerMetaData))]

where "Customer" is the name of the entity.

Then, manually create MetaData classes for each of your entities. You can actually use a T4 template for that, too, if you want, but not have it run all the time.

The Metadata classes look like this...

public class CustomerMetaData
{

    [StringLength(150, ErrorMessage="Maximum length is 150 characters.")]
    [Required(ErrorMessage="CustomerName is required.")]
    public virtual string CustomerName
    {
        get;
        set;
    }
    public virtual Nullable<int> Type
    {
        get;
        set;

    }

    // ... etc ...
}

As you can see, you attach the rules to the MetaData class, thus abstracting it from the generated entity class.

0

精彩评论

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

关注公众号