Brandon Turpy
Brandon Turpy

Reputation: 921

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

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
}

Upvotes: 2

Views: 2053

Answers (1)

WeskerTyrant
WeskerTyrant

Reputation: 511

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

Upvotes: 1

Related Questions