[英]How to Add Attributes to .cs file generated by Entity Framework
I am creating a ASP.net MVC web app and trying to add validation attributes to a ClientsTbl.cs file I have generated from a SQL server using entity framework. 我正在创建一个ASP.net MVC Web应用程序,并尝试将验证属性添加到使用实体框架从SQL Server生成的ClientsTbl.cs文件中。 I have done scaffolding and created the view and the controller for the Table(Model), but for some reason the scaffold did not recognize the primary key column as a primary key.
我已经完成了脚手架并为Table(Model)创建了视图和控制器,但是由于某种原因,脚手架无法将主键列识别为主键。 On top of that it will not let me add attributes in [].
最重要的是,它不允许我在[]中添加属性。 I can't even change the field description that appears above the views form text box.
我什至无法更改显示在视图表单文本框上方的字段描述。 How do I do the above in the following class?
在下一堂课中我该如何做?
namespace Testit.Models
{
using System;
using System.Collections.Generic;
public partial class ClientsTbl
{
public ClientsTbl()
{
this.ProgramClientTbls = new HashSet<ProgramClientTbl>();
}
public int id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int CenterId { get; set; }
public string MiddleName1 { get; set; }
public string MiddleName2 { get; set; }
public System.DateTime DateAdded { get; set; }
public virtual CenterTbl CenterTbl { get; set; }
public virtual ICollection<ProgramClientTbl> ProgramClientTbls { get; set; }
}
}
You can create a metadata class to do that. 您可以创建一个元数据类来做到这一点。 For example, if Id, FirstName, and LastName are required fields, you can create a new class like below.
例如,如果Id,FirstName和LastName是必填字段,则可以创建一个如下所示的新类。
public class ClientsTblMetadata
{
[Required()]
public int Id { get; set; }
[Required()]
public string FirstName { get; set; }
[Required()]
public string LastName { get; set; }
}
Then you need to add a new partial class with a MetadataType
attribute. 然后,您需要添加一个带有
MetadataType
属性的新局部类。 Please make sure that this class is located under the same namespace, otherwise it won't work. 请确保此类位于相同的名称空间下,否则它将无法正常工作。
namespace Testit.Models
{
[MetadataType(typeof(ClientsTblMetadata))] // you need this line of code.
public partial class ClientsTbl
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.