在LINQ TO SQL 中使用MVC3中的DataAnnotations 【MetadataType】

原文发布时间为:2011-04-07 —— 来源于本人的百度文章 [由搬家工具导入]

http://stackoverflow.com/questions/1535662/asp-net-mvc-linq-to-sql-data-annotation-validation

让自动生成model不会覆盖自己添加过的model属性[attribute] MetadataType

在LINQ TO SQL 中使用MVC3中的DataAnnotations 【MetadataType】

==========================

1、LINQ TO SQL 自动生成的dbml 文件 不用去动它

2、设计一个对应实体类的接口,如Album 实体类,则可以设计如下接口

public interface IAlbum
    {
        int AlbumId { get; set; }
        int GenreId { get; set; }
       // int ArtistId { get; set; }
        [Required(ErrorMessage = "Be Required")]
        string Title { get; set; }
        decimal Price { get; set; }
        string AlbumArtUrl { get; set; }
    }

3、在写一个 Album 的部分类 实现接口 IAlbum

  public partial class Album : IAlbum
    {

    }

4、在部分类上面添加特性 [MetadataType(typeof(IAlbum))]

   [MetadataType(typeof(IAlbum))]
    public partial class Album : IAlbum
    {

    }

=====草稿代码如下:

namespace TestLin.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel;
    using System.Web.Mvc;

    [MetadataType(typeof(IAlbum))]
    [Bind(Exclude = "AlbumId")]
    public partial class Album : IAlbum
    {

    }

    public interface IAlbum
    {
        int AlbumId { get; set; }
        int GenreId { get; set; }
        int ArtistId { get; set; }
        [Required(ErrorMessage = "Be Required")]
        string Title { get; set; }
        decimal Price { get; set; }
        string AlbumArtUrl { get; set; }
    }
}

 

原文:

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:

1、If there is a mismatch between the name in your LINQ class and the name in your interface, the compiler will flag it for you

2、An interface can not be instantiated, so this protects class users from accidentally instatntiating the metadata type

3、If you use Resharper (or similar), the interface can be automatically extracted from the LINQ class

4、An interface is less verbose than an empty class

5、If you program against interfaces rather than classes (which is a good practice), then you've already got an interface you can use as your metadata type

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))]
publicclassUser:IUser

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

[Required]     
[StringLength(50,ErrorMessage="Username cannot exceed 50 characters")]
stringUsername{get;set;}
原文地址:https://www.cnblogs.com/handboy/p/7163969.html