简体   繁体   English

如何自动从EF设置文本框的maxlengh属性?

[英]How to automatically set maxlengh property for textbox from EF?

I am using normal helper EditFor to bind data to html controls. 我正在使用普通的助手EditFor将数据绑定到html控件。

For completeness, here a example: 为了完整起见,下面是一个示例:

@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @maxlength= 100, @class = "form-control" } })

To set maxlength for string fields, i need to explicitly set the attribute in every view that uses the same table field and there are many views and strings value in the data model. 要为字符串字段设置maxlength ,我需要在使用相同表字段的每个视图中显式设置属性,并且数据模型中有很多视图和字符串值。

Doing this in every page is error prone. 在每个页面中执行此操作很容易出错。 Changes is size will break the app if a place is forgotten. 如果忘记了位置,则更改大小会破坏应用程序。

How to pass the length directly from EF Model? 如何直接从EF模型传递长度?

The easiest option is to add the [MaxLength(50)] attribute to the model property. 最简单的选项是将[MaxLength(50)]属性添加到模型属性。 For example: 例如:

public class SomeModel
{
    [MaxLength(50)]
    public string SomeProperty { get; set; }
}

You can then omit the maxlength property from the call to @Html.EditorFor() and it will be taken from the model metadata. 然后,您可以从对@Html.EditorFor()的调用中忽略maxlength属性,该属性将从模型元数据中获取。

You can use the Fluent API to configure a maximum length for a property. 您可以使用Fluent API配置属性的最大长度。 In this example, targeting SQL Server this would result in the nvarchar(500) data type being used. 在此示例中,针对SQL Server,这将导致使用nvarchar(500)数据类型。

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Test>()
                .Property(b => b.Description)
                .HasMaxLength(500);
        }

Or You can use the Data Annotations to configure a maximum length for a property. 或者,您可以使用数据注释来配置属性的最大长度。

public class Test
    {
        [MaxLength(500)]
        public string Description{ get; set; }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM