[英]The entity type 'List<string>' requires a primary key to be defined in my mstest
[英]The entity type 'List<string>' requires a primary key to be defined
獲取“實體類型 List<string'> 需要定義主鍵。” 使用 .NET 6 構建一個 Web API。
以下是我的 Model 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; }
}
}
你必須確保你有一張桌子
public List<String> Images { get; set; } = new List<String>
因為數據庫無法在創建的表中引用未知的列表大小。
改變
public List<String> Images { get; set; } = new List<String>
至
public List<ImageUri> Images { get; set; } = new List<ImageUri>
並創建一個類。
public class ImageUri
{
[Key]
public int Id { get; set; }
public string Uri { get; set; } = null!;
}
您可以將 List 轉換為帶分隔符的字符串並以這種方式使用它,而不必創建一個特殊的 class 來基本上保存一個字符串。
modelBuilder.Entity<Berk>(x =>
{
x.HasKey(y => y.BerkId);
x.Property(y => y.TheList)
.HasConversion(
from => string.Join(";", from),
to => string.IsNullOrEmpty(to) ? new List<string>() : to.Split(';', StringSplitOptions.RemoveEmptyEntries).ToList(),
new ValueComparer<List<string>>(
(c1, c2) => c1.SequenceEqual(c2),
c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
c => c.ToList()
)
);
});
public class Berk
{
[Key]
public int BerkId { get; set; }
public List<string> TheList { get; set; }
}
HasConversion 將值作為分隔字符串存儲在數據庫中,在您使用它時將其拆分到列表中,然后在保存時再次將其重新加入。 只需選擇一個不會出現在您的任何字符串中的定界符。
今天下午這讓我很煩惱,希望它能幫助別人。
我們在通過部分 class 擴展生成 model 的 EF 時遇到了這個問題。部分 class 包含兩個不能反映基礎 data.table 的屬性,並生成錯誤:“實體類型‘列表’需要定義主鍵”。 最后,我們的解決方案是包含 [NotMapped] 屬性,如下所示:
[NotMapped] public List<string> Roles { get; set; } = new List<string>(); [NotMapped] public List<string[]> Claims { get; set; } = new List<string[]>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.