开发者

Using UIHint in combination with LINQ to SQL generated class

开发者 https://www.devze.com 2023-03-09 05:20 出处:网络
I used LINQ to SQL to generate a dbml file which contains the database model for my database table. I want to use UIHint to let MVC present some fields as DropDownLists or Checkboxes in edit mode. But

I used LINQ to SQL to generate a dbml file which contains the database model for my database table. I want to use UIHint to let MVC present some fields as DropDownLists or Checkboxes in edit mode. But if I change the file, it will be lost if it's been regenerated. How should I solve that issue? I'm quite new to MVC and still learning. I've set up a controller with views for all CRUD elements, but now I'm finetuning and I'm running in开发者_JAVA百科to this problem.


Since Linq-to-SQL auto-generates partial classes, you'll need to create a partial 'buddy class' where you will add your Data Annotations. Your buddy class mirrors portions of the auto-generated class that you need to modify. You tie them together with [MetadataType(typeof(BuddyClassName))] The partial buddy class and the auto-generated partial class will be merged together when you compile your project.

In an example given that:

  • Your namespace is "Project.Models"
  • Your Linq-To-Sql class is called "Products"

    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; }
        }
      }
    }
    

These articles were very helpful:

  1. ScottGu: ASP.NET MVC 2: Model Validation
  2. How to: Validate Model Data Using DataAnnotations Attributes
  3. Validating with Data Annotation Validators


If you are going to use the entities directly you should create a partial class and add your annotations there. This way when the model is regenerated you will not lose your annotations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号