如何使用 EF 将数组属性映射到分隔字符串数据库字段?

发布于 2024-10-15 19:01:01 字数 552 浏览 3 评论 0原文

我有一个带有数组属性的对象,我想将其作为分隔字符串保留在数据库中。如何将该属性映射到数据库中的字段,反之亦然?

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

不完整的配置类:

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

对于此示例,“Roles”属性在访问数据库时将转换为“roleA、roleB、roleC”,然后在从数据库读取时转换回数组。某处是否存在数据映射事件?

I have an object with an array property that I want to persist in the database as a delimited string. How to I Map that property to the field in the database and vice versus?

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

Incomplete Config Class:

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

For this example the "Roles" property would be converted to "roleA,roleB,roleC" when going to the database and then transformed back to an array when read from the database. Is there an on data mapping event somewhere?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沒落の蓅哖 2024-10-22 19:01:01

您需要一个附加属性来将 String 包装并转换为 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 能够为您管理一切,并意味着您的数据存储一致且可访问。逗号分隔的字符串使用起来并不是特别愉快,并且不应该存储在数据库中。

You need an additional property that wraps and converts the String into a 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);
    }
  }
}

The preferred solution would of course be to add a new table to your database called Role, and have a one-many relationship so that a User has many Roles. This will allow EF to manage everything for you, and means your data is stored coherently and accessibly. Comma delimited strings are not particularly pleasant to work with and shouldn't be stored in databases.

世俗缘 2024-10-22 19:01:01

您必须提供额外的属性来实现字符串和数组之间的转换逻辑。您将映射该属性并忽略 Roles 属性。

You have to provide additional property which will implement conversion logic between string and array. You will map that property and ignore Roles property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文