问题描述
我的mvc3应用程序有问题,我需要创建一些Validation东西.但是我没有普通的模型类,因为我已经将EF与数据库优先方法结合使用了.
i have a problem with my mvc3 application, i need to create some Validation stuff. but i dont have a normal model class because i have used EF with the database first approach.
我不能只打开类并编写如下内容:
i can not just open the class and write something like:
[Required]
[StringLength(10)]
如何解决这个问题?
推荐答案
您可以使用 MetadataType属性.因此,让我们假设EF向您吐出了您无法修改的以下类:
You could use the MetadataType attribute. So let's suppose that EF spit at your face the following class which you cannot modify:
public partial class Foo
{
public string Bar { get; set; }
}
现在您可以扩展它,因为它是部分类:
Now you could extend it since it is a partial class:
[MetadataType(typeof(FooMetadata))]
public partial class Foo
{
}
,然后定义元数据:
public class FooMetadata
{
[Required]
[StringLength(10)]
public string Foo { get; set; }
}
或者,直接丢弃数据注释,并使用真实的验证框架,例如 FluentValidation.NET (我将使用并强烈建议),允许您以流畅的方式在模型上表达复杂的验证规则,并具有与ASP.NET MVC完美集成,并且还允许您优雅地单独测试验证逻辑.
Or, simply throw data annotations away and use a real validation framework such as FluentValidation.NET (which I use and strongly recommend) allowing you to express complex validation rules on your models in a fluent manner, has an excellent integration with ASP.NET MVC and also allows you to elegantly unit test your vaildation logic in isolation.
这篇关于当我首先将EF与数据库一起使用时,如何在asp.net mvc3中添加Validation内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!