如何使用 EF 将数组属性映射到分隔字符串数据库字段?
我有一个带有数组属性的对象,我想将其作为分隔字符串保留在数据库中。如何将该属性映射到数据库中的字段,反之亦然?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要一个附加属性来将
String
包装并转换为String[]
。首选的解决方案当然是在数据库中添加一个名为
Role
的新表,并具有一对多关系,以便一个User
拥有多个Roles< /代码>。这将使 EF 能够为您管理一切,并意味着您的数据存储一致且可访问。逗号分隔的字符串使用起来并不是特别愉快,并且不应该存储在数据库中。
You need an additional property that wraps and converts the
String
into aString[]
.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 aUser
has manyRoles
. 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.您必须提供额外的属性来实现字符串和数组之间的转换逻辑。您将映射该属性并忽略 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.