简体   繁体   中英

Asp.net Core List<enum> in model

I'm trying to include a list of enums in my model, however I'm encountering some issues. In my first approach I tried this:

public class Ferrata
{
    [JsonProperty(PropertyName = "Id")]
    public int ID { get; set; }

    [JsonProperty(PropertyName = "PlaceName")]
    public string Name { get; set; }

    [JsonIgnore]
    public double Lat { get; set; }

    [JsonIgnore]
    public double Lon { get; set; }

    public string GeoLat { get { return Lat.ToString(); } }

    public string GeoLong { get { return Lon.ToString(); } }

    public List<Difficulty> Difficulty { get; set; }
}

public enum Difficulty { F, PD, AD, D, TD, ED };

However using enum in such way results with an exception when I try to perform any operation with ef:

System.InvalidOperationException: The property 'Ferrata.Difficulty' could not be mapped, because it is of type 'List' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it.

Following some advice on the internet, I created a standalone class for holding my enum values like this:

public class FerrataDifficulty
{
    public int ID { get; set; }
    public Difficulty Difficulty { get; set; }

    public FerrataDifficulty(Difficulty difficulty)
    {
        Difficulty = difficulty;
    }
}

After changing my original Ferrata class to take list of FerrataDifficulty the program compiles, however there are two problems: * Even though in my database initializer I initialize the difficulties when I debug the code they seem to be null * When I try to delete the database entries through the application I get the following error:

SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_FerrataDifficulty_Ferrata_FerrataID". The conflict occurred in database "ViaFerrata1", table "dbo.FerrataDifficulty", column 'FerrataID'.

I would appreciate if anyone could point out what I'm doing wrong and what's the best practice on including a list of enums in the model in asp.net core.

I managed to solve the problem by using enum flags:

[Flags]
[JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public enum Difficulty
{
    F = 1,
    PD = 2,
    AD = 4,
    D = 8,
    TD = 16,
    ED = 32
};

This seems to be the simplest way to achieve exactly what I needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM