英文:
How can i store list of values entity framework with mysql
问题
我想在我的 `Project` 实体中存储工人的 Id 列表。
```csharp
public class Project
{
[Required] [Key] public Guid id { set; get; }
...其他字段
[AllowNull] public List<Guid> workers { set; get; }
}
但是 MySql 不支持数组类型,当我配置模型时
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>(x =>
{
x.HasKey(y => y.id);
x.Property(y => y.workers);
});
}
我遇到错误 The property 'Project.workers' is of type 'List<Guid>' which is not supported by the current database provider.
那么,使用 EF 存储数组类型的最佳方法是什么?
<details>
<summary>英文:</summary>
I want to store list of Ids of workers in my `Project` entity.
public class Project
{
[Required] [Key] public Guid id { set; get; }
...Other fields
[AllowNull] public List<Guid> workers { set; get; }
}
But MySql doesn't support array type and when i'm configuring model
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>(x =>
{
x.HasKey(y => y.id);
x.Property(y => y.workers);
});
}
i have an error `The property 'Project.workers' is of type 'List<Guid>' which is not supported by the current database provider.`
So, what is the best way so store array type with EF?
</details>
# 答案1
**得分**: 1
你可以使用Conversion将列表合并为字符串并反序列化它。
如下所示;
```csharp
modelBuilder.Entity<Project>(x =>
{
x.HasKey(y => y.id);
x.Property(y => y.workers).HasConversion(x => JsonConvert.SerializeObject(x), // to converter
x => JsonConvert.DeserializeObject<List<Guid>>(x));
});
英文:
you can use Conversion to combine list to string and deserialize It.
like below;
modelBuilder.Entity<Project>(x =>
{
x.HasKey(y => y.id);
x.Property(y => y.workers).HasConversion(x => JsonConvert.SerializeObject(x), // to converter
x => JsonConvert.DeserializeObject<List<Guid>>(x));
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论