Search code examples
asp.net-mvcmodeldefault-value

How do I set a default value in a model without having a column for it?


I am trying to set a default value to a property in my model

public string fruitType = "Apple";
public string FruitType
{
    get { return fruitType; }
    set { fruitType = value; }
}

The issue that I am having however is FruitType isn't a column in my database table, so it is throwing an error. Is it possible for me to set this even though the column does not exist?


Solution

  • Mark your property as NotMapped and use the default value :

    public string fruitType = "Apple";
    [NotMapped]
    public string FruitType
    {
        get { return fruitType; }
        set { fruitType = value ?? fruitType; }
    }