实体类型 'List<string>' 需要定义主键

The entity type 'List<string>' requires a primary key to be defined

获取“实体类型 List 需要定义主键。”使用 .NET 6 构建 Web API.

以下是我的模型 class 定义“销售”:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SalesAPI.Data
{
    public class SalesItem
    {
     
        [Key]
        [Required]
        public Guid UserID { get; set; }

        [Required]
        [MinLength(5)]
        [MaxLength(75)]
        public String Title { get; set; }  = String.Empty;

        [Required]
        [MinLength(5)]
        public String Description { get; set; } = String.Empty;

        public List<String> Images { get; set; } = new List<String>();

        [Required]
        public DateTime ListingTime { get; set; }

        public String Location { get; set; } = String.Empty;

        public String ContactInfo { get; set; } = String.Empty;
    }
}

下面是我的DBContext class:

using Microsoft.EntityFrameworkCore;
using SalesAPI.Controllers;
    
namespace SalesAPI.Data
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) { }

        public DbSet<SalesItem> SalesItems { get; set; }
        
    }
}

您必须确保 table

public List<String> Images { get; set; } = new List<String>

因为数据库无法在创建的 table 中引用未知列表大小。

改变

public List<String> Images { get; set; } = new List<String>

public List<ImageUri> Images { get; set; } = new List<ImageUri>

并创建一个 class.

public class ImageUri
{
    [Key]
    public int Id { get; set; }
    public string Uri { get; set; } = null!;
}