使用数据库优先模型 (EF 5) 向模型添加验证 [英] Adding validation to model with Database First model (EF 5)

查看:25
本文介绍了使用数据库优先模型 (EF 5) 向模型添加验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何向模型状态添加验证错误.我知道如何将验证注释添加到我的模型类中.问题是先用Database,我不想动生成的代码,因为当我重新生成的时候,我会失去我的自定义.我总是尝试在部分中进行自定义,但是您不能在部分中为现有属性添加注释.

I know how to add validation errors to the model state. I know how to add the validation annotations to my model classes. The problem is that with Database first, I don't want to touch the generated code, because when I regenerate, I will lose my customization. I always try to customize in partials, but you can't add annotation to an existing property in a partial.

这里的最佳实践是什么?

What is best practice here?

推荐答案

你需要利用MetadataTypeAttribute

做这样的事情:

创建一个新的类文件,将其保存在与您的分部类相同的命名空间中.即使您从数据库更新模型,这个新类也会保留您的验证规则.修改新类文件的内容,如下所示,更改为您的规范等.

Create a new class file, keep it in the same namespace as your partial class. This new class will keep your validation rules even if you update your Model from Database. Modify the contents of your new class file like below, change to your specifications ,etc.

[MetadataTypeAttribute(typeof(YourCustomClassForValidation))]
public partial class Person
{
   // No need to put anything here because you already defined these properties
}

public class YourCustomClassForValidation
{
   [DisplayName("Full Name")]
    public string name { get; set; }
}

这篇关于使用数据库优先模型 (EF 5) 向模型添加验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆