如何使用Entity Framework和MySQL存储值列表?

huangapple go评论81阅读模式
英文:

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&#39;t support array type and when i&#39;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 &#39;Project.workers&#39; is of type &#39;List&lt;Guid&gt;&#39; 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&lt;Project&gt;(x =&gt;
        {
            x.HasKey(y =&gt; y.id);
            x.Property(y =&gt; y.workers).HasConversion(x =&gt; JsonConvert.SerializeObject(x), // to converter
                                   x =&gt; JsonConvert.DeserializeObject&lt;List&lt;Guid&gt;&gt;(x));
        });

huangapple
  • 本文由 发表于 2023年1月9日 12:48:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定