ASP.NET MVC,LINQ到SQL数据注释验证 [英] ASP.NET MVC, Linq to SQL Data Annotation Validation

查看:107
本文介绍了ASP.NET MVC,LINQ到SQL数据注释验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现数据诠释我的LINQ到SQL对象。生成的.dbml文件,我不知道如何将数据添加注释的对象而不触及生成的源$ C ​​$ C。

I'm trying implement Data Annotation to my Linq to SQL objects. The .dbml file is generated and I'm not sure how to add data annotation to the objects without touching the generated source code.

我试图数据的注释添加到一个单独的部分类的对象,但它不承认它,没有意义的Intelli要么。

I tried to add data annotations to the a separate partial class of the object, but its not recognizing it, no Intelli sense either.

推荐答案

正如我在原来的回答这个问题时说,你应该使用的接口。雷后发布的答案(这是标记为已接受)说要用一个类。这是没有那么好。接口是由于以下原因,一个更好的选择:

As I said in my original answer to this question, you should use an interface. The answer posted after mine (which was marked as Accepted) said to use a class. This is not as good. An interface is a better option for the following reasons:


  • 如果有名称之间在你的LINQ类的名称与接口不匹配,编译器将其标记为你

  • 一个接口不能被实例化,所以这个保护类用户意外instatntiating元数据类型

  • 如果您使用ReSharper的(或类似),该接口可以自动从LINQ类提取

  • 接口是不是空类更简洁

  • 如果您对编程接口而不是类(这是一个很好的做法),那么你已经得到了你可以为你的元数据类型使用接口

有关一个叫做类,说用户,创建一个接口为它(说'IUSER'),然后更新您的部分用户类的定义如下:

For a class called, say "User", create an interface for it (say 'IUser'), and then update the definition of your partial User class as follows:

[MetadataType(typeof(IUser))]
public class User : IUser

然后,在你IUSER界面,添加适当的数据注解属性的属性:

Then, in your IUser interface, add appropriate Data Annotation attributes to the properties:

[Required]       
[StringLength(50, ErrorMessage = "Username cannot exceed 50 characters")]
string Username { get; set; }

这篇关于ASP.NET MVC,LINQ到SQL数据注释验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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