Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to persist SmartFlagEnum in EF Core #379

Open
zyofeng opened this issue Mar 13, 2023 · 3 comments
Open

How to persist SmartFlagEnum in EF Core #379

zyofeng opened this issue Mar 13, 2023 · 3 comments

Comments

@zyofeng
Copy link

zyofeng commented Mar 13, 2023

Currently im using the following syntax in CodeFirst but EF Core complains about AccountRoles not having a primary key (I assume this was due to the missing convertor)

Is there a guide on how to use SmartFlagEnum with EFCore?

public virtual ICollection Roles { get; internal set; } = new HashSet();

public sealed class AccountRoles : SmartFlagEnum {
public static readonly AccountRoles Primary = new AccountRoles("Primary", 1 << 0);
public static readonly AccountRoles Secondary = new AccountRoles("Secondary", 1 << 1);
}

@zyofeng
Copy link
Author

zyofeng commented Mar 16, 2023

Tagging @AFM-Horizon

@cuneytatik84
Copy link

Same problem, any improvement

@FairlieAgile
Copy link

Most of the functions that come with SmartFlagEnum return an IEnumerable (e.g. .FromValue). So there are 2 options:

  1. Use IEnumberable in your entity e.g.
    public IEnumerable<EnvironmentEnum> Environments { get; private set; } = default!;

And then convert it when you configure the Entity:

builder.Property(x => x.Environments)
    .HasConversion(v => ConvertToDatabaseValue(v), v => ConvertFromDatabaseValue(v))
  private int ConvertToDatabaseValue(IEnumerable<EnvironmentEnum> value)
  {
    int intValue = value.Sum(x => x.Value);
    // Log the conversion value
    Console.WriteLine($"Converting {value} to {intValue}");
    return intValue;
  }
  private IEnumerable<EnvironmentEnum> ConvertFromDatabaseValue(int value)
  {
    return EnvironmentEnum.FromValue(value);
  }
  1. Use an INT to store the value and convert as you save/retrieve. This option suited me best:
 public int Environments { get; private set; } = default!; 

  public void UpdateEnvironment(string environments)
  {
    Environments = EnvironmentEnum.FromName(environments).Sum(x => x);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants