我想在我的模型中包含一个枚举列表,但是我遇到了一些问题。在我的第一个方法我试过这样:Asp.net Core List <enum> in model
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 };
但是使用与异常这样的方式导致枚举当我尝试用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.
继互联网上的一些意见,我创建一个独立的类握着我的枚举值是这样的:
public class FerrataDifficulty
{
public int ID { get; set; }
public Difficulty Difficulty { get; set; }
public FerrataDifficulty(Difficulty difficulty)
{
Difficulty = difficulty;
}
}
改变我原来的费拉塔下课后采取FerrataDifficulty的列表中的程序编译,但有一个再两个问题: *即使在我的数据库初始化我初始化的困难,当我调试的代码,他们似乎是空 *当我试图通过应用程序,我得到以下错误删除的数据库条目:
SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_FerrataDifficulty_Ferrata_FerrataID". The conflict occurred in database "ViaFerrata1", table "dbo.FerrataDifficulty", column 'FerrataID'.
如果有人能指出我做错了什么,以及在asp.net核心模型中包含枚举列表的最佳做法是什么,我将不胜感激。
您提供的代码没有任何问题。您需要发布实际导致错误的代码。您还需要告诉我们您正在尝试做什么。 – Guy
您不能使用“难度”实体,因为只有具有an的类才可以是实体。使其成为具有Id(或使用阴影属性)和难度属性的类,然后映射它。或者将enum作为一个标志并将其用作非集合属性'public Difficulty Difficulty {get;组; }'如果你想存储多个 – Tseng
如果难度枚举是字符串,你需要提供枚举类型作为字符串,但它更好地使用静态类与公共字符串常量或给枚举一个类型(int,short,string ...等),并允许它按需转换,因为您应该将其视为自定义类型而不是自动内置类型 –