Entity Framework, Saving a Collection of Enums

主宰稳场 提交于 2021-01-24 09:35:14

问题


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

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'.

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.

My question is what is the best way for us to store the list of phone restrictions in Entity Framework?

CODE

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
}

回答1:


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"));


来源:https://stackoverflow.com/questions/46677113/entity-framework-saving-a-collection-of-enums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!