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

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

How can i store list of values entity framework with mysql

问题

  1. 我想在我的 `Project` 实体中存储工人的 Id 列表。
  2. ```csharp
  3. public class Project
  4. {
  5. [Required] [Key] public Guid id { set; get; }
  6. ...其他字段
  7. [AllowNull] public List<Guid> workers { set; get; }
  8. }

但是 MySql 不支持数组类型,当我配置模型时

  1. protected override void OnModelCreating(ModelBuilder modelBuilder)
  2. {
  3. modelBuilder.Entity<Project>(x =>
  4. {
  5. x.HasKey(y => y.id);
  6. x.Property(y => y.workers);
  7. });
  8. }

我遇到错误 The property 'Project.workers' is of type 'List<Guid>' which is not supported by the current database provider.

那么,使用 EF 存储数组类型的最佳方法是什么?

  1. <details>
  2. <summary>英文:</summary>
  3. 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; }
}

  1. 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);
});
}

  1. 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.`
  2. So, what is the best way so store array type with EF?
  3. </details>
  4. # 答案1
  5. **得分**: 1
  6. 你可以使用Conversion将列表合并为字符串并反序列化它。
  7. 如下所示;
  8. ```csharp
  9. modelBuilder.Entity<Project>(x =>
  10. {
  11. x.HasKey(y => y.id);
  12. x.Property(y => y.workers).HasConversion(x => JsonConvert.SerializeObject(x), // to converter
  13. x => JsonConvert.DeserializeObject<List<Guid>>(x));
  14. });
英文:

you can use Conversion to combine list to string and deserialize It.
like below;

  1. modelBuilder.Entity&lt;Project&gt;(x =&gt;
  2. {
  3. x.HasKey(y =&gt; y.id);
  4. x.Property(y =&gt; y.workers).HasConversion(x =&gt; JsonConvert.SerializeObject(x), // to converter
  5. x =&gt; JsonConvert.DeserializeObject&lt;List&lt;Guid&gt;&gt;(x));
  6. });

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:

确定