简体   繁体   English

实体框架说我试图用相同的键插入多个实体,但是我不认为我在

[英]Entity Framework says I'm trying to insert multiple entities with the same key, but I don't think I am

I'm using EF for code-first migrations. 我正在使用EF进行代码优先的迁移。 When I update-database, I get this error message in the Nuget console: 当我更新数据库时,我在Nuget控制台中收到以下错误消息:

Conflicting changes detected. 检测到冲突的更改。 This may happen when trying to insert multiple entities with the same key. 尝试使用相同的键插入多个实体时,可能会发生这种情况。

Here is my config.cs file with the Seed method: 这是我的带有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>
{

}

} }

I set the Id's of Theory and Prop as the Key which I thought EF would auto generate. 我将理论和道具的ID设置为我认为EF会自动生成的密钥。 I didn't set any for props and commented them out on the theories, so I'm a bit confused as to what's happening. 我没有为道具设置任何东西,也没有对道具进行评论,所以对于发生的事情我有些困惑。

In your AddOrUpdate method, you're using a field to match, but you're never setting it. 在您的AddOrUpdate方法中,您正在使用一个字段进行匹配,但从未设置它。

You should either set the id, or use another field to match. 您应该设置ID,或使用其他字段进行匹配。 Ex: 例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架 - “两个对象之间的关系无法定义”错误,但我认为我使用的是相同的上下文 - Entity Framework - “The relationship between the two objects cannot be defined” error, but I think I'm using the same context 我不认为我要修改此收藏集 - I don't think I'm modifying this collection 我该怎么做? 我不想使用实体框架在数据库中添加相同的记录 - How can I do it ? I don't want to add same record in database with Entity Framework 如何取消任务 - 尝试使用 CancellationTokenSource,但我想我不明白这个概念 - How to cancel a task - trying to use a CancellationTokenSource, but I think I don't get the concept 我正在尝试从实体框架返回XML数据 - I am trying to return XML data from Entity Framework 我用这个代码得到一个新的错误,这没有用,我想我删除了一些东西,但我不确定是什么 - I m getting a new error with this code, that didn't use to happen and I think I deleted something but I am not sure what 我是否需要在同一个解决方案中将多个实体框架模型放在他们自己的项目中? - Am I required to put multiple Entity Framework Models in their own projects in the same solution? 多个添加的实体可能在实体框架中具有相同的主键 - Multiple added entities may have the same primary key in Entity Framework 我正在尝试运行一个循环,但我遇到了一个我不知道如何修复的错误 - I'm trying to run a loop, and I'm getting an error which I don't know how to fix 没有默认数据库时的Entity Framework 6和迁移 - Entity Framework 6 and migration when I don't have a default Database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM