[英]Validate entry length based on database-first entity model
My client is using c#, EF6.0 database-first, and webforms. 我的客户使用的是c#,EF6.0数据库优先和webforms。 I want to validate for the max length of a textbox entry in an aspx form.
我想验证aspx形式的文本框条目的最大长度。 I don't want to hardcode the max-length client-side or server-side, instead I want to retrieve it from the EF6.0 entity model so that it matches the length of the underlying database-first field.
我不想对最大长度的客户端或服务器端进行硬编码,而是想从EF6.0实体模型中检索它,以使其与基础数据库优先字段的长度匹配。 The field is an nvarchar(40).
该字段是一个nvarchar(40)。 (If I was working in a 'code-first' scenario I would try using validation annotations, but this doesn't seem possible in 'database-first').
(如果我在“代码优先”的情况下工作,我会尝试使用验证注释,但这在“数据库优先”中似乎不可能)。
How can I do the validation based on the underlying database-first field length? 如何根据基础数据库优先字段长度进行验证?
您可以为生成的POCO创建局部类,并在其中应用将在重新生成时不会被覆盖的验证: 将数据注释添加到由实体框架生成的类中
I found a good solution. 我找到了一个很好的解决方案。 Since asp.net 4.5 it is possible to use Data-Annotation attributes with WebForms and Entity Frameworks.
从asp.net 4.5开始,可以在WebForms和Entity Frameworks中使用数据注释属性。 Specifically:
特别:
using System.ComponentModel.DataAnnotations;
namespace Diary.DataAccess.Model
{
// Accommodate EF database-first regeneration (required for webforms)
[MetadataType(typeof(UserDetailMetaData))]
public partial class UserDetail
{
}
// Add the Data-Annotation attribute to the Title model-property.
public class UserDetailMetaData
{
[MaxLength(40, ErrorMessage="Title must not be more than 40 characters long.")]
public string Title { get; set; }
}
}
(This doesn't retrieve the constant from the database-first metadata, but does keep it in one place.) (这不会从数据库优先的元数据中检索常数,而是将其保留在一个位置。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.