user3818229
user3818229

Reputation: 1647

Is it possible to add value constraints for string property via Entity Framework?

I'm implementing user's language setting to store it in database:

[Table("User")]
public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Language { get; set; }

    [NotMapped]
    public CultureInfo Culture => string.IsNullOrWhiteSpace(Language) ? Thread.CurrentThread.CurrentCulture : new CultureInfo(Language);
}

Is it possible to specify Language values can be? For example: "sl-SI" or "hr-HR" or "ru-RU" only? Thanks in advance!

Upvotes: 1

Views: 1064

Answers (2)

Emad
Emad

Reputation: 3949

Maybe you can create an enum of supported languages and use helper for strings:

public enum SupportedLanguages
{
    [Description("sl-SL")]
    Sl,
    [Description("hr-HR")]
    Hr,
    [Description("ru-RU")]
    Ru
}

public static string GetDescription(this Enum value)
{            
    FieldInfo field = value.GetType().GetField(value.ToString());

    DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
                as DescriptionAttribute;

    return attribute == null ? value.ToString() : attribute.Description;
}

Then use this like this

[Table("User")]
public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    private SupportedLanguages language;
    public SupportedLanguages Language 
    { 
        get { return language; }
        set 
        {
            if(!Enum.IsDefined(typeof(SupportedLanguages), value))
                throw new ArgumentOutOfRangeException();
            language = value;
        }
    }

    [NotMapped]
    public CultureInfo Culture => string.IsNullOrWhiteSpace(Language.GetDescription()) ? Thread.CurrentThread.CurrentCulture : new CultureInfo(Language.GetDescription());
}

Upvotes: 3

Slava Utesinov
Slava Utesinov

Reputation: 13508

You should do it at migration:

public override void Up()
{  
    Sql("ALTER TABLE Users ADD CONSTRAINT LanguageCnst CHECK (Language in ('sl-SI', 'hr-HR', 'ru-RU'))");
}

public override void Down()
{
    Sql('ALTER TABLE Users DROP CONSTRAINT LanguageCnst');
}

And add some code to User:

[Table("User")]
public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Language { get; protected set; }

    public setLanguage(string value)
    {
        if(new[]{"sl-SI", "hr-HR", "ru-RU"}.Contains(value))
            Language = value;
    }

    [NotMapped]
    public CultureInfo Culture => string.IsNullOrWhiteSpace(Language) ? Thread.CurrentThread.CurrentCulture : new CultureInfo(Language);
}

Upvotes: 0

Related Questions