You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Entity Data Model中添加尺寸列表属性?

解决Product实体添加尺寸列表属性的问题

1. 修改Product实体

在实体中添加尺寸列表属性,必须初始化列表避免空引用异常:

namespace API.Entities
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public long Price { get; set; }
        public string PictureUrl { get; set; }
        public string Type { get; set; }
        public string Brand { get; set; }
        public int QuantityInStock { get; set; }
        // 添加尺寸列表并初始化
        public List<string> Sizes { get; set; } = new List<string>();
    }
}

2. 修正种子数据赋值方式

种子数据中可通过两种方式赋值,确保列表实例有效:

new Product
{
    Name = "Shirt",
    Description = "Text.",
    Price = 20000,
    PictureUrl = "url",
    Brand = "Brand",
    Type = "Shirt",
    QuantityInStock = 10,
    // 方式1:显式创建List实例
    Sizes = new List<string> { "L", "M", "XL" }
    // 方式2:依赖实体的初始化,直接使用集合初始化器
    // Sizes = { "L", "M", "XL" }
},

3. 配置EF Core数据映射

EF Core默认无法直接将List<string>映射到数据库列,需配置为JSON格式存储(适用于EF Core 5及以上版本):
在你的DbContext的OnModelCreating方法中添加配置:

using Microsoft.EntityFrameworkCore;
using API.Entities;
using System.Text.Json;

public class YourDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>()
            .Property(p => p.Sizes)
            // 将List<string>序列化为JSON字符串存储
            .HasConversion(
                v => JsonSerializer.Serialize(v, new JsonSerializerOptions()),
                v => JsonSerializer.Deserialize<List<string>>(v, new JsonSerializerOptions())
            )
            // 设置数据库列类型为支持大文本的类型
            .HasColumnType("nvarchar(max)");
    }
}

常见失败原因

  • 未初始化Sizes属性:直接使用集合初始化器时,属性为null会抛出空引用异常
  • EF Core未配置映射:数据库中无对应列或列类型不支持存储JSON,导致数据无法持久化

内容的提问来源于stack exchange,提问作者peter92a

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:47:03