简体   繁体   中英

Entity framework code first - create table and insert data from existing table into newly created one,

I'm using EF code first and I want to create a new table and insert values from an existing table into it.

public override void Up()
        {
            CreateTable(
                "dbo.UserCulture",
                c => new
                {
                    UserCultureId = c.Int(false, true),
                    Id = c.Int(false),
                    IsSelected = c.Boolean(false),
                    Culture = c.String(false, 10),
                    UserLevel = c.Int(false),
                    CurrentScore = c.Int(false),
                    TimelinePercentage = c.String(false, 3),
                    NumberOfGamesPlayed = c.Int(false)

                })
                .PrimaryKey(k => k.UserCultureId)
                .ForeignKey("dbo.AskUser", k => k.Id)
                .Index(t => t.Id);

            Sql("INSERT INTO UserCulture(UserCultureId, Id, IsSelected, Culture, UserLevel, CurrentScore, TimelinePercentage, NumberOfGamesPlayed)" +
                "SELECT newid(), UserId, 1, CreatedCulture, UserLevel, CurrentScore, TimelinePercentage, NumberOfGamesPlayed FROM AskUser");

        }

When I ran this migration it created the table but it was empty. Does anyone know what I should do?

newid() is for uniqueidentifier? Can you try removing that column in the insert statement?

Sql("INSERT INTO UserCulture(Id, IsSelected, Culture, UserLevel, CurrentScore, TimelinePercentage, NumberOfGamesPlayed)" +
                "SELECT UserId, 1, CreatedCulture, UserLevel, CurrentScore, TimelinePercentage, NumberOfGamesPlayed FROM AskUser");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM