How can I match an array property with a db string separator using EF?

I have an object with the array property that I want to save in the database as a delimited string. How to match this property with a field in the database and vice versa?

public class User() {
  public int Id { get; set; }
  public string[] Roles { get; set; }
}

Incomplete configuration class:

public class UserConfig : EntityTypeConfiguration<User> {
  public UserConfig() {
    this.Property(u => u.Roles).__???__
    this.Map(u => u.Properties<string[]>(r => r.Roles).__???__))
      .HasColumnName("roles");
  }
}

In this example, the "Roles" property will be converted to "roleA, roleB, roleC" when going to the database, and then, when accessing the database, it will be converted back to an array. Is there a data display event somewhere?

+3
source share
2 answers

You need an additional property that wraps and converts Stringto String[].

public class User() {
  public int Id { get; set; }
  public string Roles { get; set; }
  public string[] RolesArray 
  { 
    get
    {
      return Roles.Split(',').ToArray();
    }
    set
    {
      Roles = String.Join(',', value);
    }
  }
}

, , Role "-", User Roles. EF , . - .

+5

, . .

+1

Source: https://habr.com/ru/post/1790208/


All Articles