heisenberg
heisenberg

Reputation: 1312

Entity Framework: Saving a collection of enum values

I have one Entity Plan that can have multiple BodyAreas.

public class Plan
{
    public Guid Id { get; set; }
    public DateTimeOffset CreatedAt { get; set; }

    public string Name { get; set; }

    public TrainningGoal? TrainningGoal { get; set; }

    public virtual ICollection<Video> Videos { get; set; }

    public BodyArea BodyAreas { get; set; }
}

I first thought about creation a PlanBodyArea Relation, but then I thought about using the [Flags] attribute instead. So I've changed my enum to:

[Flags]
public enum BodyArea
{
    Legs = 0,
    Booty = 1,
    Arms = 2,
    Shoulders = 4,
    Bicep = 8,
    Tricep = 16,
    Chest = 32,
    Back = 64,
    Core = 128,
    UpperBody = 256,
    LowerBody = 1024,
    FullBody = 2048
}

Problem is that now I don't know how to make the mapping from the Json to ViewModel to my entity.

public class PlanViewModel : IViewModel
{
    [Required]
    public string Name { get; set; }
    public long Duration { get; set; }
    public Guid Id { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
    public ICollection<BodyArea> BodyAreas { get; set; }
    public TrainningGoal TrainningGoal { get; set; }
    public ICollection<VideoViewModel>? Videos { get; set; }
}

I have the following but of course it doesn't work:

        CreateMap<PlanViewModel, Plan>()
            .ForMember(dest => dest.BodyAreas, opt => opt.MapFrom(src => src.BodyAreas))
            .ForMember(dest => dest.Videos, opt => opt.Ignore());

Upvotes: 2

Views: 586

Answers (1)

Felix Castor
Felix Castor

Reputation: 1675

A flag would only need a single property not a collection.

public BodyArea BodyAreas { get; set; }

To have multiple body areas:

BodyAreas = BodyArea.Chest | BodyArea.Shoulders;

To check if a body area is included. You use the HasFlag method to check the BodyAreas property.

BodyAreas.HasFlag(BodyArea.Shoulders);

Enum.HasFlag() MSDN

On a side note, I would suggest BodyArea.None = 0, to allow a default selection.

Upvotes: 2

Related Questions