如何存储 IEnumerable<string> 的属性?在 Cosmos 表中,使用 EF Core 3.1 [英] How do I store a property of IEnumerable<string> in a Cosmos table, with EF Core 3.1
问题描述
我的项目使用 EF Core 3.1,并将 Azure Cosmos 作为数据库.
My project is using EF Core 3.1, and targeting Azure Cosmos as the database.
我有一个这样的实体:
public class MyEntity
{
public IEnumerable<string> Names {get;set;}
... other fields
}
我希望以这样的 Cosmos 文档结尾:
That I would like to end up in a Cosmos document like this:
{
"Names": ["Name1", "Name2"]
}
使用实体 (IEnumerable
) 我得到错误:
With the entity as is (IEnumerable<string>
) I get the error:
无法映射属性MyEntity.Names",因为它属于IEnumerable"类型,它不是受支持的原始类型或有效的实体类型.
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.
如果我将实体更改为:
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);
});
}
文档如下所示:
{
"Id": "XXXXXX",
"Names:" [
{},
{}
],
}
所以我改变了 OnModelCreating:
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));
});
}
然后我得到:
{
"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.
任何帮助将不胜感激.
推荐答案
这里有一个和你类似的问题:实体框架 - 代码优先 - 无法存储列表
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.
正如上面的链接所解释的那样,您可以在 OnModelCreating 方法中进行:
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));
这篇关于如何存储 IEnumerable<string> 的属性?在 Cosmos 表中,使用 EF Core 3.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!