【问题标题】:Entity Framework says I'm trying to insert multiple entities with the same key, but I don't think I am实体框架说我正在尝试使用相同的键插入多个实体,但我不认为我是
【发布时间】:2015-09-13 05:17:10
【问题描述】:

我正在使用 EF 进行代码优先迁移。当我更新数据库时,我在 Nuget 控制台中收到此错误消息:

检测到有冲突的更改。尝试插入具有相同键的多个实体时可能会发生这种情况。

这是我使用 Seed 方法的 config.cs 文件:

internal sealed class Configuration : DbMigrationsConfiguration<MiracleMachine.data.ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(MiracleMachine.data.ApplicationDbContext context)
    {
        context.Props.AddOrUpdate(
            p => p.PropId,
            new Prop() { PropName = "sharpie" },
            new Prop() { PropName = "coin" },
            new Prop() { PropName = "playing cards" },
            new Prop() { PropName = "coffee mug" },
            new Prop() { PropName = "phone" },
            new Prop() { PropName = "keys" },
            new Prop() { PropName = "sunglasses" },
            new Prop() { PropName = "headphones" },
            new Prop() { PropName = "ring" },
            new Prop() { PropName = "lighter" }
            );
        context.SaveChanges();

        context.Theories.AddOrUpdate(
            t => t.TheoryId,
            new Theory()
            {
                // TheoryId = 0,
                TheoryName = "Production",
                TheoryDescription = "Make it appear out of nowhere!"
            },
            new Theory()
            {
                // TheoryId = 1,
                TheoryName = "Vanish",
                TheoryDescription = "Make it vanish into thin air!"
            },
            new Theory()
            {
                // TheoryId = 2,
                TheoryName = "Transportation",
                TheoryDescription = "Make it vanish, and then reappear somewhere impossible!"
            },
            new Theory()
            {
                // TheoryId = 3,
                TheoryName = "Transformation", // This uses TWO props
                TheoryDescription = "Cause one of these items to change into the other item!"
            },
            new Theory()
            {
                // TheoryId = 4,
                TheoryName = "Multiplication",
                TheoryDescription = "Magically duplicate this item again and again!"
            },
            new Theory()
            {
                // TheoryId = 5,
                TheoryName = "Penetration", // This uses TWO props
                TheoryDescription = "Cause the two items to inexplicably pass through each other"
            },
            new Theory()
            {
                // TheoryId = 6,
                TheoryName = "Restoration",
                TheoryDescription = "Destroy the item in some way. Restore it."
            },
            new Theory()
            {
                // TheoryId = 7,
                TheoryName = "Levitation",
                TheoryDescription = "Make the item float in mid-air!"
            });
        context.SaveChanges();

        //////////////////////////////////////////// The following seeds user data

        // ApplicationUser table seeder
        UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(context);
        UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);

        RoleStore<Role> roleStore = new RoleStore<Role>(context);
        RoleManager<Role> roleManager = new RoleManager<Role>(roleStore);

        if (!roleManager.RoleExists("Admin"))
            roleManager.Create(new Role { Name = "Admin" });

        if (!roleManager.RoleExists("User"))
            roleManager.Create(new Role { Name = "User" });

        IdentityResult result = null; // Sets the result to null. Used for error checking.

        /////////// Admin (1)
        ApplicationUser admin1 = userManager.FindByName("MagicRawb");

        if (admin1 == null)
        {
            admin1 = new ApplicationUser
            {
                FirstName = "Rob",
                LastName = "Greenlee",
                UserName = "magicrawb",
                Email = "magicrawb@test.com",
                Gender = Gender.Male
            };
        }

        result = userManager.Create(admin1, "asdfasdf");
        if (!result.Succeeded)
        {
            string error = result.Errors.FirstOrDefault();
            throw new Exception(error);
        }

        userManager.AddToRole(admin1.Id, "Admin"); // Add user1 to Admin role
        admin1 = userManager.FindByName("magicrawb"); // Assign user1 data to variable user1

        /////////// Admin (2)
        ApplicationUser admin2 = userManager.FindByName("admin2");

        if (admin2 == null)
        {
            admin2 = new ApplicationUser
            {
                FirstName = "Bekah",
                LastName = "Sells",
                UserName = "admin2",
                Email = "admin2@test.com",
                Gender = Gender.Female
            };
        }

        result = userManager.Create(admin2, "asdfasdf");
        if (!result.Succeeded)
        {
            string error = result.Errors.FirstOrDefault();
            throw new Exception(error);
        }

        userManager.AddToRole(admin2.Id, "Admin"); // Add user1 to Admin role
        admin1 = userManager.FindByName("admin2"); // Assign user1 data to variable user1

        /////////// User (1)
        ApplicationUser user1 = userManager.FindByName("user1");

        if (user1 == null)
        {
            user1 = new ApplicationUser
            {
                FirstName = "Lance",
                LastName = "Burton",
                UserName = "user1",
                Email = "user1@test.com",
                Gender = Gender.Male
            };
        }

        result = userManager.Create(user1, "asdfasdf");
        if (!result.Succeeded)
        {
            string error = result.Errors.FirstOrDefault();
            throw new Exception(error);
        }

        userManager.AddToRole(user1.Id, "User"); // Add user1 to Admin role
        user1 = userManager.FindByName("user1"); // Assign user1 data to variable user1

        /////////// User (2)
        ApplicationUser user2 = userManager.FindByName("user2");

        if (user2 == null)
        {
            user2 = new ApplicationUser
            {
                FirstName = "David",
                LastName = "Stone",
                UserName = "user2",
                Email = "user2@test.com",
                Gender = Gender.Male
            };
        }

        result = userManager.Create(user2, "asdfasdf");
        if (!result.Succeeded)
        {
            string error = result.Errors.FirstOrDefault();
            throw new Exception(error);
        }

        userManager.AddToRole(user1.Id, "User"); // Add user1 to Admin role
        user2 = userManager.FindByName("user2"); // Assign user1 data to variable user1

        context.SaveChanges();
        Database.SetInitializer(new MyInitializer());
    }
}

internal class MyInitializer : MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>
{

}

}

我将 Id 的 Theory 和 Prop 设置为我认为 EF 会自动生成的 Key。我没有为 props 设置任何东西,而是对理论进行了评论,所以我对正在发生的事情感到有些困惑。

【问题讨论】:

  • 请创建一个SSCCE。
  • 我查了这个,老实说我不确定如何。包括整个项目?
  • 包含更少的代码;仅应包含相关并证明问题的代码。在上下文中显示哪些代码在添加或删除时会引入问题。在构建 SSCCE 时,我经常“发现自己的问题”,这很好,因为在此过程中,不相关的代码部分会被删除,直到可以清楚地看到核心问题。
  • 我需要一段时间来单独运行每一行来找出是哪一行导致了这种情况。它不会弄乱我已经拥有的数据库表吗?我是否只是删除数据库并为每一行重新启动?一旦我弄清楚如何做这一切,我会发布另一个问题。
  • 您使用 TheoryId 作为 AddOrUpdate 的键,但您从未设置 TheoryId。这无济于事......

标签: c# entity-framework


【解决方案1】:

在您的 AddOrUpdate 方法中,您使用了一个字段来匹配,但您从未设置它。

您应该设置 id,或者使用其他字段进行匹配。例如:

context.Props.AddOrUpdate(
    p => p.PropName,
    new Prop() { PropName = "sharpie" },
    new Prop() { PropName = "coin" },
    new Prop() { PropName = "playing cards" },
    new Prop() { PropName = "coffee mug" },
    new Prop() { PropName = "phone" },
    new Prop() { PropName = "keys" },
    new Prop() { PropName = "sunglasses" },
    new Prop() { PropName = "headphones" },
    new Prop() { PropName = "ring" },
    new Prop() { PropName = "lighter" });

【讨论】:

  • 我将其更改为 p.PropName 并且还取消了对 TheoryId 的注释。仍然收到相同的多个实体错误
  • 那么它可能在 userStore 或 roleStore 中。我不知道这是怎么回事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 2017-12-23
相关资源
最近更新 更多