问题描述
|
我使用LINQ to SQL生成了一个dbml文件,该文件包含我的数据库表的数据库模型。我想使用UIHint让MVC在编辑模式下将某些字段显示为DropDownLists或Checkboxes。但是,如果我更改文件,则如果重新生成该文件,它将丢失。我该如何解决这个问题?我是MVC的新手,现在还在学习。我已经为所有CRUD元素设置了带有视图的控制器,但是现在我正在微调,并且遇到了这个问题。
解决方法
由于Linq-to-SQL自动生成部分类,因此您需要创建部分\'buddy class \,在其中添加数据注释。您的伙伴类反映了您需要修改的自动生成类的部分。您可以将它们与[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; }
}
}
}
这些文章非常有帮助:
ScottGu:ASP.NET MVC 2:模型验证
如何:使用DataAnnotations属性验证模型数据
使用数据注释验证器进行验证
, 如果要直接使用实体,则应创建局部类并在其中添加注释。这样,在重新生成模型时,您将不会丢失注释。