How do I store a property of IEnumerable<string> in a Cosmos table, with EF Core 3.1

青春壹個敷衍的年華 提交于 2020-12-12 04:01:34

问题


My project is using EF Core 3.1, and targeting Azure Cosmos as the database.

I have an entity like this:

public class MyEntity
{
    public IEnumerable<string> Names {get;set;}
    ... other fields
}

That I would like to end up in a Cosmos document like this:

{
    "Names": ["Name1", "Name2"]
}

With the entity as is (IEnumerable<string>) I get the error:

The property 'MyEntity.Names' could not be mapped, because it is of type 'IEnumerable' which is not a supported primitive type or a valid entity type.

If I change the entity to:

public class NameEntity
{
    public string Name {get;set;}
}
public class MyEntity
{
    public IEnumerable<NameEntity> Names {get;set;}
    ... other fields
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyEntity>(e =>
    {
        e.OwnsMany(p => p.Identifiers);
    });
}

The document looks like this:

{
    "Id": "XXXXXX",
    "Names:" [
       {},
       {}
    ],
}

So I change the OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyEntity>(e =>
    {
        e.OwnsMany(p => p.Identifiers, o=> o.HasKey(k=>k.Name));
    });
}

And I then get:

{
  "Names": [
    {
        "Name": "<string1>",
        "Id": "XXXX"
    },
    {
        "Identifier": "<string2>",
        "Id": "XXXX"
    }
]}

I've also looked at value converters, but I think that is more for converting property values between types, rather than converting an entity to a string.

Any help would be appreciated.


回答1:


Here is a similar question to yours : Entity Framework - Code First - Can't Store List<String>

Currently, it's not possible to store a list of primitive type (string included).

Your best bet would be to store the list as a string in your database, and when you fetch it you transform it back to a list.

As the link above explained it, you can do in your OnModelCreating method :

modelBuilder.Entity<YourEntity>()
        .Property(e => e.Strings)
        .HasConversion(
            v => string.Join(',', v),
            v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));


来源:https://stackoverflow.com/questions/62474945/how-do-i-store-a-property-of-ienumerablestring-in-a-cosmos-table-with-ef-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!