简体   繁体   English

根据数据库优先实体模型验证条目长度

[英]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.

相关问题 对数据库优先实体框架模型的更改 - Changes to a database-first Entity Framework model 实体框架数据库优先不能创建正确的模型 - Entity Framework database-first doesn't create the correct model 在实体框架中刷新使用数据库优先方法模型创建的实体中的数据 - Refresh the data in entity created using database-first approach model in Entity Framework 是否存在实体框架7数据库优先POCO生成器? - Is there an Entity Framework 7 Database-First POCO Generator? 实体框架数据库优先-SQL Server - Entity Framework database-first with SQL Server 实体框架6,数据库优先和自定义多元化 - Entity Framework 6, Database-First & Custom Pluralization 无法进行数据库优先模型生成 - Cannot do database-first model generation 如何使用 C# 中的数据库优先方法生成具有所有 CRUD 操作的存储库和模型/实体类 - how to generate the Repository and model/entity classes with all CRUD operations using database-first apporach in C# 从数据库更新模型时出错(EntityFramework数据库优先) - Error in Updating the model from database (EntityFramework Database-First) 首先使用实体​​框架数据库对结果进行预过滤 - Pre-filtering results with entity framework database-first
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM