簡體   English   中英

實體框架說我試圖用相同的鍵插入多個實體,但是我不認為我在

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

我正在使用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設置為我認為EF會自動生成的密鑰。 我沒有為道具設置任何東西,也沒有對道具進行評論,所以對於發生的事情我有些困惑。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM