[英]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: 但是,当我尝试使用ef执行任何操作时,以这种方式使用enum会导致异常:
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.
System.InvalidOperationException:无法映射属性“ Ferrata.Difficulty”,因为它的类型为“列表”,它不是受支持的原始类型或有效的实体类型。 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: 将原始Ferrata类更改为FerrataDifficulty列表后,程序会进行编译,但是存在两个问题:*即使在数据库初始化程序中,我在调试代码时也会初始化困难,它们似乎为空*在尝试删除数据库时通过应用程序输入以下错误:
SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_FerrataDifficulty_Ferrata_FerrataID".
SqlException:DELETE语句与REFERENCE约束“ FK_FerrataDifficulty_Ferrata_FerrataID”发生冲突。 The conflict occurred in database "ViaFerrata1", table "dbo.FerrataDifficulty", column 'FerrataID'.
数据库“ ViaFerrata1”的表“ dbo.FerrataDifficulty”的列“ 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. 如果有人能指出我做错了什么,以及在asp.net核心中的模型中包含枚举列表的最佳做法,我将不胜感激。
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. 这似乎是实现我所需要的最简单的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.