如何检查我尝试创建的种子数据是否已在我的数据库中?

How do I check if the seeded data I try to create is already in my database?

提问人:Wintrow Vestrit 提问时间:11/4/2023 最后编辑:Dale KWintrow Vestrit 更新时间:11/5/2023 访问量:52

问:

尝试更新数据库时,我偶然发现了以下错误:

违反 PRIMARY KEY 约束“PK_AvatarBase”。无法在对象“dbo”中插入重复的键。阿凡达基地”。重复的键值为 (1)。
该声明已被终止。

我正在尝试更新我的数据库,但我的数据库有一些种子数据,这是我第一次创建数据库时我需要的方法。DbContextOnModelCreating

我的是以下内容:DbContext

using Microsoft.EntityFrameworkCore;
using TurtleQuest.Models;

namespace TurtleQuest.Data
{
    public class TurtleQuestConnection : DbContext
    {
        public DbSet<Player> Players { get; set; }
        public DbSet<CardMA> cardMAs { get; set; }
        public DbSet<CardTORF> cardTORF { get; set; }
        public DbSet<Avatar> Avatars { get; set; }
        public DbSet<Game> Games { get; set; }

        public TurtleQuestConnection(DbContextOptions<TurtleQuestConnection> options) : base(options) { }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<AvatarBase>().HasData(
            new 
            { 
                Id = 1,
                Name = "BaseImage",
                ImagePath = "/Images/Frenky/Lines.png"
            }
            );
            modelBuilder.Entity<AvatarColor>().HasData(
            new
            {
                Id = 1,
                Name = "Base",
                ImagePath = "/Images/Frenky/Colors/base.png"
            },
            new
            {
                Id = 2,
                Name = "Blue",
                ImagePath = "/Images/Frenky/Colors/Blue.png"
            },
            new
            {
                Id = 3,
                Name = "Purple",
                ImagePath = "/Images/Frenky/Colors/Purple.png"
            },
            new
            {
                Id = 4,
                Name = "Red",
                ImagePath = "/Images/Frenky/Colors/Red.png"
            },
            new
            {
                Id = 5,
                Name = "Yellow",
                ImagePath = "/Images/Frenky/Colors/Yellow.png"
            }
            );
            modelBuilder.Entity<AvatarHat>().HasData(
            new
            {
                Id = 1,
                Name = "Top Hat",
                ImagePath = "/Images/Frenky/Accesories/Hat1.png"
            },
            new
            {
                Id = 2,
                Name = "Cap",
                ImagePath = "/Images/Frenky/Accesories/Hat2.png"
            }
            );
        }


    }
}

任何帮助将不胜感激。

sql-server 实体框架 模型视图控制器 dbcontext

评论


答: 暂无答案