Entity Framework required with default value

I have an EF Code First setup, I have a specific column that is marked as required for annotation. This column has a default constraint specified in the database.

What I'm trying to do is let the user enter a value in the form, but if they omit it, use the default value from the database. I was not lucky.

If I do not enter anything, a mandatory error is displayed on the form. If I add an annotation [DatabaseGenerated(DatabaseGeneratedOption.Computed)], the value the user enters is ignored and always uses the default database.

+4
source share
2 answers

, , .

:

[DefaultValueSql("'A'")]
[DefaultValue("A")]
[Required]

DefaultValueSql - , SQL . DefaultValue . , DRY, (, ).

/ ActionResult :

    if (model.ActiveIndicator == null)
    {
        model.ActiveIndicator = ((DefaultValueAttribute)(model.GetType().GetProperty("ActiveIndicator").GetCustomAttributes(typeof(DefaultValueAttribute), true).First())).Value.ToString();
        ModelState["ActiveIndicator"].Errors.Clear(); // Removes Model Error
    }

DefaultValue, , ModelState , ModelState.IsValid .

, (, ), , -, , .

: TryUpdateModel, ModelState :

    if (model.ActiveIndicator == null)
    {
        var defValue = ((DefaultValueAttribute)(model.GetType().GetProperty("ActiveIndicator").GetCustomAttributes(typeof(DefaultValueAttribute), true).First())).Value.ToString();
        ModelState.SetModelValue("ActiveIndicator", new ValueProviderResult(defValue, "", CultureInfo.InvariantCulture));
        ModelState["ActiveIndicator"].Errors.Clear(); // Removes Model Error
    }
0

, .

,

if (!String.IsNullOrWhiteSpace(value))
    //set the value in the database entry based on user input

, - .

, , "".

0

Source: https://habr.com/ru/post/1652403/


All Articles