实体框架核心添加移民抛出“已经添加了具有相同密钥的项目。键:myproject.model.mycontext

问题描述 投票:0回答:2

An item with the same key has already been added. Key: MyProject.Model.MyContext

where是我的ASP.NET核心项目,是我的DBContext类。

我的dbcontext类看起来像

MyProject

要添加的表是

MyContext
表,并且要添加的两个列在
namespace MyProject.Model
{
    public class MyContext : DbContext
    {
        public MyWorker Worker { get; private set; }

        /// <summary>
        /// initialize the worker instance to get the crud methods of the database
        /// </summary>
        public MyContext()
        {
            Worker = new MyWorker(this);
        }

        public static string GetConnectionString()
        {
            return Startup.ConnectionString;
        }

        /// <summary>
        /// Our own context must override the OnConfiguring Method from Ef Core to set the right connection
        /// Connectionstring is set in appsettings.json
        /// </summary>
        /// <param name="_builder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder _builder)
        {
            _builder.UseSqlServer(GetConnectionString());
        }

        protected override void OnModelCreating(ModelBuilder _modelBuilder)        {
            _modelBuilder.Entity<User>().HasIndex(u => u.MailAdress).IsUnique();
        }

        public DbSet<Project>  Projects  { get; set; }
        public DbSet<Document> Documents { get; set; }
        public DbSet<DocData>  DocsData  { get; set; }
        public DbSet<User>     Users     { get; set; }
        public DbSet<UCLSystem>   Systems   { get; set; }
    }


    public class DesignTimeContextFactory : IDesignTimeDbContextFactory<MyContext>
    {
        public MyContext CreateDbContext(string[] args)
        {
            IConfiguration configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var builder = new DbContextOptionsBuilder<MyContext>();

            var connectionString = configuration["Connectionstrings:MyConnection"];

            return new MyContext();
        }
    }
}

表中。

Systems

标志上,我将获得以下输出
documents

	
在我的情况下,我需要删除生成的快照CS文件并重新生成迁移。
    

当您试图丢弃具有多个/重复的外键/单个表的表格时,通常会发生这种错误。

因此,首先您必须将外键放在单个迁移中。之后放下桌子。
    

在我的情况下,这是一个具有多个db-contexts
的迁移执行器项目中的复制式错误错误
c# entity-framework entity-framework-core entity-framework-migrations
2个回答
8
投票

固定在正确的上下文中解决了问题


8
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.