如何在Owned实体中使用List<string>?EF Core配置求助
问题描述
模型代码
public class Product { public Guid guid { get; set; } = Guid.NewGuid(); public required string Name { get; set; } public List<string>? Tags { get; set; } = new(); public List<ProductProperties>? Properties { get; set; } } [Owned] public class ProductProperties { public string? Size { get; set; } public string? Color { get; set; } // 取消注释此行会报错 // public List<string>? Photos { get; set; } }
模型配置代码
modelBuilder.Entity<Product>() .Property(p => p.Tags).HasConversion<StringListConverter>(); modelBuilder.Entity<Product>().OwnsMany( product => product.Properties, prodProp => { prodProp.ToJson(); });
问题现象
取消ProductProperties中Photos属性的注释后,执行迁移时触发错误:
The entity type 'List' requires a primary key to be defined.
If you intended to use a keyless entity type, call 'HasNoKey' in
'OnModelCreating'.
需求:通过Fluent API为Photos配置StringListConverter,且不将ProductProperties作为独立数据库实体。
解决方案
由于Product.Properties被配置为JSON列,且ProductProperties是Owned类型,需要在OwnsMany的配置内部针对Photos属性设置转换器。修改后的配置代码如下:
modelBuilder.Entity<Product>() .Property(p => p.Tags).HasConversion<StringListConverter>(); modelBuilder.Entity<Product>().OwnsMany( product => product.Properties, prodProp => { prodProp.ToJson(); // 为Photos属性添加转换器 prodProp.Property(pp => pp.Photos) .HasConversion<StringListConverter>(); });
修改后EF Core会通过StringListConverter将Photos列表转换为逗号分隔字符串,嵌入到Properties的JSON列中,不会将其识别为需要主键的实体类型。
内容的提问来源于stack exchange,提问作者FLICKER
相关产品推荐
相关产品推荐

