如何向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
相关产品推荐
相关产品推荐

