I would like to define a class for different strings which Entity Framework Core will recognise and apply certain rules without data annotations.
For instance I would like to replace the following string property with a string object:
[MaxLength(20)]
public string PhoneNumber { get; set; }
to be replaced with:
public PhoneNumber PhoneNumber { get; set; }
In this scenario, the PhoneNumber class will have a max length of 20 when called by Entity Framework Core.
public class PhoneNumber
{
private readonly string value;
private readonly long maxLength;
public PhoneNumber(string value, long maxLength = long.MaxValue)
{
if (value != null && value.Length > maxLength)
{
throw new InvalidOperationException(string.Format("Value is limited to {0} characters.", maxLength.ToString()));
}
this.value = value;
this.maxLength = maxLength;
}
public override string ToString()
{
return value;
}
public static implicit operator PhoneNumber(string phoneNumber)
{
return new PhoneNumber(phoneNumber);
}
public static implicit operator String(PhoneNumber phoneNumber)
{
return phoneNumber.value;
}
}