asp.net mvc 3-使用UIHint结合LINQ生成SQL类



我使用LINQ to SQL生成了一个dbml文件,该文件包含我的数据库表的数据库模型。我想使用UIHint让MVC在编辑模式下将一些字段显示为DropDownList或Checkbox。但如果我更改了文件,如果重新生成它,它就会丢失。我应该如何解决这个问题?我是MVC的新手,还在学习。我已经为所有CRUD元素设置了一个带有视图的控制器,但现在我正在进行微调,遇到了这个问题。

由于Linq to SQL自动生成分部类,您需要创建一个分部"伙伴类",在其中添加数据注释。您的好友类镜像了您需要修改的自动生成类的部分。您可以使用[MetadataType(typeof(BuddyClassName))]将它们绑定在一起。当您编译项目时,部分伙伴类和自动生成的部分类将合并在一起。

在给定的示例中:

  • 您的命名空间为"Project.Models"
  • 您的Linq-To-Sql类称为"产品"

    using System.ComponentModel.DataAnnotations;
    namespace Project.Models
    {
      [MetadataType(typeof(ProductsMeta))]
      public partial class Products
      {
        // You can extend the products class here if desired.
        public class ProductsMeta
        {
          // This is a Linq-to-Sql Buddy Class      
          // In here you can add DataAnnotations to the auto-generated partial class
          [Key]
          public int ProductKey { get; set; }
          [Display (Name = "Product Name")]
          [Required(ErrorMessage = "Product Name Required")]
          [StringLength(255, ErrorMessage = "Must be under 255 characters")]
          public string ProductName { get; set; }
          [UIHint("MultilineText")]
          public string Description { get; set; }
        }
      }
    }
    

这些文章非常有用:

  1. ScottGu:ASP.NET MVC 2:模型验证
  2. 如何:使用DataAnnotations属性验证模型数据
  3. 使用数据注释验证器进行验证

如果要直接使用实体,则应创建一个分部类并在其中添加注释。这样,当重新生成模型时,就不会丢失注释。

最新更新