Entity Framework 4.1 code first approach: how to define length of properties

社会主义新天地 提交于 2019-12-03 14:44:58

问题


As the title implies:

how is it possible to tell Entity Framework 4.1 in code first approach, that i do want some properties (in particular of type string) to have a length of 256, or nvarchar(max), or...

So if this is for example my model

public class Book{
   public string Title { get; set; } //should be 256 chars
   public string Description {get;set} //should be nvarchar(max)
}

how could it be defined?

Thanks in advance!


回答1:


In EF4.1 RTW default length is nvarchar(max) for SQL Server and nvarchar(4000) for SQL CE. To change the length use either StringLength or MaxLength annotations or fluent mapping HasMaxLength:

[StringLength(256)]
public string Title { get; set; }

Or

[MaxLength(256)]
public string Title { get; set; }

Or

modelBuilder.Entity<Book>()
            .Property(p => p.Title)
            .HasMaxLength(256);



回答2:


As is stated in my comment, it's simple.
Just use [StringLength(1000)] or [MaxLength] from DataAnnotation.



来源:https://stackoverflow.com/questions/5678190/entity-framework-4-1-code-first-approach-how-to-define-length-of-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!