Reputation: 804
My requirement is configuing the string length mapping globally, but also can use MaxLengthAttribute to configue a property specially. Here's my code:
public class StringLengthConvention
: IConfigurationConvention<PropertyInfo, StringPropertyConfiguration>
{
public void Apply(
PropertyInfo propertyInfo,
Func<StringPropertyConfiguration> configuration)
{
StringAttribute[] stringAttributes = (StringAttribute[])propertyInfo.GetCustomAttributes(typeof(StringAttribute),true);
if (stringAttributes.Length > 0)
{
configuration().MaxLength = stringAttributes [0].MaxLength;
}
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add<StringLengthConvention>();
}
public class ContentInfo
{
// ...
[MaxLength(200)]
[String]
public string TitleIntact { get; set; }
// ...
}
My problem is the "MaxLength" can't work anymore. Do i need to check if the property has a MaxLengthAttribute before applying the global configuration in the StringLengthConvention.Apply()?
Upvotes: 1
Views: 1234
Reputation: 880
What would work in this situation is to create a lightweight convention specifying the MaxLength property for strings. In this situation the convention would set the max length of the property for all strings except where it was already configured by an annotation, with the fluent API, or by another convention.
In your OnModelCreate method add the following code to set your default MaxLength:
modelBuilder.Properties<string>()
.Configure(c => c.HasMaxLength(DefaultStringLength));
there is a walkthough of conventions here: http://msdn.microsoft.com/en-us/data/jj819164.aspx make sure to take a look at the "Further Examples" at the bottom of the page
Upvotes: 2