Développement

Astuces de développement

Outils pour utilisateurs

Outils du site


langages:asp_csharp:ef:migrer_une_base_de_donnees_existante

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Prochaine révision
Révision précédente
langages:asp_csharp:ef:migrer_une_base_de_donnees_existante [2019/09/24 12:39]
jonathan créée
langages:asp_csharp:ef:migrer_une_base_de_donnees_existante [2019/09/24 12:41] (Version actuelle)
jonathan
Ligne 2: Ligne 2:
  
 https://entityframework.net/identity-insert https://entityframework.net/identity-insert
 +
 +In Entity Framework, when you have a primary key field such as Id or AuthorId which is mapped to IDENTITY column in the database, it works well when you insert data.
 +
 +In some cases, you might need to insert explicit values into a SQL Server IDENTITY column.
 +To do so, you need to enable IDENTITY_INSERT before calling SaveChanges() manually.
 +Let's say we want to create a new author with explicit AuthorId value.
 +
 +<code csharp>
 +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"},
 +    }
 +};
 +</code>
 +
 +But you can't insert an author with explicit AuthorId value directly in the identity column, so you will need to turn on the IDENTITY_INSERT before calling SaveChanges().
 +
 +<code csharp>
 +using (var context = new BookStore())
 +{
 +    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");
 +}
 +</code>
 +
 +Unfortunately, when SaveChanges is called the explicit identity value is ignored, and a new value generated by the database is used.
  
 The solution is to create a new context class which will inherit our main context class and overrides the OnModelCreating. The solution is to create a new context class which will inherit our main context class and overrides the OnModelCreating.
langages/asp_csharp/ef/migrer_une_base_de_donnees_existante.1569321589.txt.gz · Dernière modification: 2019/09/24 12:39 de jonathan