Développement

Astuces de développement

Outils pour utilisateurs

Outils du site


langages:asp_csharp:ef:migrer_une_base_de_donnees_existante

Ceci est une ancienne révision du document !


Récupérer des données dans une base de données existante en vue d’une migration

https://entityframework.net/identity-insert

The solution is to create a new context class which will inherit our main context class and overrides the OnModelCreating.

public class TempBookStore : BookStore
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Author>()
          .Property(a => a.AuthorId)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        base.OnModelCreating(modelBuilder);
    }
}

In the OnModelCreating function we can set the attribute on the entity to not generate auto values for AuthorId. You will also need to make sure to wrap the SQL command and the row in a transaction.

using (var context = new TempBookStore())
{
    using (var transaction = context.Database.BeginTransaction())
    {
        Author author = new Author()
        {
            AuthorId = 1001,
            Name = "Johny",
            Books = new List<Book>
            {
                new Book() { Title = "Learn VB.NET"},
                new Book() { Title = "C# Fundamentals for Absolute Beginners"},
            }
        };
        context.Authors.Add(author);
 
        context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[Authors] ON");
        context.SaveChanges();
        context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[Authors] OFF");
 
        transaction.Commit();
    }
}
langages/asp_csharp/ef/migrer_une_base_de_donnees_existante.1569321589.txt.gz · Dernière modification: 2019/09/24 12:39 de jonathan