Ci-dessous, les différences entre deux révisions de la page.
| 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:// | https:// | ||
| + | |||
| + | 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 = " | ||
| + | Books = new List< | ||
| + | { | ||
| + | new Book() { Title = "Learn VB.NET" | ||
| + | new Book() { Title = "C# Fundamentals for Absolute Beginners" | ||
| + | } | ||
| + | }; | ||
| + | </ | ||
| + | |||
| + | 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 = " | ||
| + | Books = new List< | ||
| + | { | ||
| + | new Book() { Title = "Learn VB.NET" | ||
| + | new Book() { Title = "C# Fundamentals for Absolute Beginners" | ||
| + | } | ||
| + | }; | ||
| + | context.Authors.Add(author); | ||
| + | | ||
| + | context.Database.ExecuteSqlCommand(@" | ||
| + | context.SaveChanges(); | ||
| + | context.Database.ExecuteSqlCommand(@" | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | Unfortunately, | ||
| 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. | ||