2014-01-14 187 views
2

我正在开发一个代码优先数据库,使用实体框架6.在实体框架代码首先

所有字符串MAXLENGTH设置我知道我可以在模型的属性设置[MaxLength(myLen)]

我想知道的是,如果可以在过滤器或自定义属性中执行此操作,以便所有字符串都采用默认值(例如250),除非直接在属性上指定。

没有这个,有没有办法改变nvarchar(max)的默认值?

回答

5

你可以做到这一点,确保所有的字符串都是由数据库供应商支持的最大长度:在你DbContext

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Properties<string>().Configure(p => p.IsMaxLength()); 
    } 

添加这个方法(或修改现有的一个)。

+0

好极了!正是我之后:)我也看到,如果我把'MaxLength'放在一个属性上,这会覆盖'modelBuilder' - 完美。 (接受答案,当它让我..) – Darren

+1

顺便说一句,我用MaxLength - 不是IsMaxLength;可能值得为未来的用户调整:) – Darren

8

实体框架6.1的推出Custom Code First Conventions

modelBuilder.Properties<string>() 
      .Configure(c => c.HasMaxLength(250)); 

约定在最后的获胜方式操作和流利的API和数据注解可用于在特定情况下

+0

现货,谢谢。我只选择另一个作为他的第一个答案:)但是,谢谢你。伟大的链接 - 只保存了一个。 – Darren

0

在EF6您覆盖公约可以使用自定义代码的第一个约定,但是您还需要有一种方法来将nvarchar(max)数据类型指定为字符串属性。所以,我想出了以下解决方案。 另见: https://msdn.microsoft.com/en-us/data/jj819164#order

/// <summary> 
/// Set this attribute to string property to have nvarchar(max) type for db table column. 
/// </summary> 
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] 
public sealed class TextAttribute : Attribute 
{ 
} 

/// <summary> 
/// Changes all string properties without System.ComponentModel.DataAnnotations.StringLength or 
/// Text attributes to use string length 16 (i.e nvarchar(16) instead of nvarchar(max) by default). 
/// Use TextAttribute to a property to have nvarchar(max) data type. 
/// </summary> 
public class StringLength16Convention : Convention 
{ 
    public StringLength16Convention() 
    { 
     Properties<string>() 
      .Where(p => !p.GetCustomAttributes(false).OfType<DatabaseGeneratedAttribute>().Any()) 
      .Configure(p => p.HasMaxLength(16)); 

     Properties() 
      .Where(p => p.GetCustomAttributes(false).OfType<TextAttribute>().Any()) 
      .Configure(p => p.IsMaxLength()); 
    } 
} 

public class CoreContext : DbContext, ICoreContext 
{ 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     //Change string length default behavior. 
     modelBuilder.Conventions.Add(new StringLength16Convention()); 
    } 
} 


public class LogMessage 
{ 
    [Key] 
    public Guid Id { get; set; } 


    [StringLength(25)] // Explicit data length. Result data type is nvarchar(25) 
    public string Computer { get; set; } 

    //[StringLength(25)] // Implicit data length. Result data type is nvarchar(16) 
    public string AgencyName { get; set; } 

    [Text] // Explicit max data length. Result data type is nvarchar(max) 
    public string Message { get; set; } 
}