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

Time:05-15

Getting "The entity type List<string'> requires a primary key to be defined." using .NET 6 to build a Web API.

The following is my Model class defining "Sales":

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;
    }
}

The following is my 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; }
        
    }
}

CodePudding user response:

You'll have to make sure you have a table for the

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

since the database isn't able to reference an unknown list size in the table created.

Change

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

To

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

and create a class.

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