1

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;
    }
}
1
  • 1
    Out of curiosity, what is the use-case you're solving for with this strategy? Also wondering if a struct would be better than a class here but I think it's always going to get allocated on the heap so maybe it doesn't matter. Commented Jul 19 at 16:20

1 Answer 1

3

You can use a Value Conversion to convert to/from a string for storage.

https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.