实体框架,保存枚举集合 [英] Entity Framework, Saving a Collection of Enums
问题描述
我有一张桌子来保存联系人的电话号码.在表格中,我对每个电话号码都有电话限制.电话限制存储为枚举,但它们可以具有多个电话限制.尝试创建迁移时,出现错误
I have a table to save phone numbers for a contact. Within the table I have phone restrictions to tie to each phone number. The phone restrictions are stored as enums, but they can have multiple phone restrictions. When I try and create a migration I get the error
无法映射属性"PhoneNumber.Restrictions",因为它的类型为"ICollection",而不是支持的原始类型或有效的实体类型.要么显式映射此属性,或使用'[NotMapped]'属性或通过忽略此属性在'OnModelCreating'中使用'EntityTypeBuilder.Ignore'.
The property 'PhoneNumber.Restrictions' could not be mapped, because it is of type 'ICollection' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
我看过一些使用标记的教程,但是上面没有太多信息/不清楚如何使用,这些教程来自5年前.
I have seen some tutorials that say to use flags, but there was not much information on it/not clear how to use and the tutorials were from 5+ years ago.
我的问题是,对于我们而言,将电话限制列表存储在Entity Framework中的最佳方法是什么?
My question is what is the best way for us to store the list of phone restrictions in Entity Framework?
代码
public class PhoneNumber
{
public int Id { get; set; }
public string PhoneNumber { get; set; }
public ICollection<PhoneRestrictions> PhoneRestrictions { get; set; }
}
public enum PhoneRestrictions
{
None = 0,
DaysOnly = 1,
DoNotCallDays = 2,
Evenings = 3,
NoWeekends = 4
}
推荐答案
实体框架只能从技术上看到 enum
值: int
.在我看来,最简单的方法是使用 Id
和 Name
/创建一个简单的定义表(
列,然后在 PhoneRestriction
)Description DbContext
中的 PhoneNumber
和 PhoneRestriction
之间创建多对多关系.
Entity Framework can only see an enum
value for what they technically are: an int
. The easiest thing to do, in my opinion, is to create a simple definition table (PhoneRestriction
) with an Id
and Name
/Description
columns, then create a many-to-many relationship between PhoneNumber
and PhoneRestriction
in your DbContext
.
modelBuilder.Entity<PhoneNumber>()
.HasMany(a => a.PhoneRestrictions)
.WithMany()
.Map(a => a.MapLeftKey("PhoneNumberId")
.MapRightKey("PhoneRestrictionId")
.ToTable("PhoneNumberPhoneRestriction"));
这篇关于实体框架,保存枚举集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!