Turn the Pluralization On
. The problem is that you model object are using singular name (Pupil
) convention, while in your database you are using pluralized names Pupils
with s
.
UPDATE
This post shows how can you turn it on or off.
Some relevant excerpt of that post:
To turn pluralization on and off
-
On the Tools menu, click Options.
-
In the Options dialog box, expand Database Tools.
Note: Select Show all settings if the Database Tools node is not visible. -
Click O/R Designer.
-
Set Pluralization of names to Enabled = False to set the O/R Designer so that it does not change class names.
-
Set Pluralization of names to Enabled = True to apply pluralization rules to the class names of objects added to the O/R Designer.
UPDATE 2
But note that, you should avoid pluralized names.
You can read here how to do it (I’ll cite it here, just in case the link gets broken).
(…) When you work with Entity Framework Code First approach, you are creating your database tables from your model classes. Usually Entity Framework will create tables with Pluralized names. that means if you have a model class called PhoneNumber, Entity framework will create a table for this class called “PhoneNumbers“. If you wish to avoid pluralized name and wants singular name like Customer , you can do it like this
In your DBContext class, Override the “OnModelCreating” method like this (…)
(…) Having this Method Overriding will avoid creating tables with pluralized names. Now it will create a Table called “PhoneNumber” , Not “PhoneNumbers” (…)
- Remove From My Forums
-
Question
-
I followed
this tutorial and wrote the following code:Module Module1 Sub Main() Dim db As New PersonModelContainer Using db db.People.Add(New Person With {.FullName = "George1"}) db.People.Add(New Person With {.FullName = "George2"}) db.People.Add(New Person With {.FullName = "George3"}) db.People.Add(New Person With {.FullName = "George4"}) db.SaveChanges() Dim per As Person Dim pipl As IQueryable(Of Person) pipl = From p In db.People Order By p.FullName Select p Console.WriteLine("All People") For Each per In pipl Console.WriteLine("- {0}", per.FullName) Next db.People.First.FullName = "Jan" db.SaveChanges() Console.WriteLine("Press any key to exit...") Console.ReadKey() End Using End Sub End Module
I then get the following error:
An error occurred while updating the entries. See the inner exception for details.
The inner exception says the following:
Default values not supported
What am I doing wrong?
Thanks for your help!
Answers
-
I’m not sure why you don’t have execute SQL , maybe it’s because you aren’t connected to the database file. Go to your database explorer and see if you can create a connection to your database file.
But long term I would recommend you install sql server management studio (SSMS), it’s very useful for connecting to a sql server or sql server CE database and being able to run queries on it and view the database objects. The VS interface for working
with databases isn’t very good.http://www.microsoft.com/download/en/details.aspx?id=7593
One thing I noticed is the auto generated code by entity framework doesn’t create an identity column on your People table. You probably want to do that. So change the create statement code that’s in your window to this:
CREATE TABLE [People] ( [Id] int identity NOT NULL, [FullName] nvarchar(4000) NOT NULL ); GO
Larcolais Gong’s database script also shows this. However Larcolais’s code is for full sql server, I don’t know if it will work with your sql ce database. I think you just need to modify your script and include the identity keyword like above.
Let me know if this works. Seems like your code is working when Larcolais and myself try it, as long as there is a valid database and identity column in the table.
Tom Overton
-
Marked as answer by
Monday, October 3, 2011 9:24 PM
-
Marked as answer by
Microsoft.EntityFrameworkCore.DbUpdateException HResult=0x80131500 Message=An error occurred while updating the entries. See the inner exception for details.
The INSERT statement conflicted with the FOREIGN KEY constraint «FK_City_Country_IdofCountry». The conflict occurred in database «MyVinylProject», table «dbo.Country», column ‘Id’.
The statement has been terminated.
-whole exception code is under code
UPDATE: Well, i fixed this with ViewModels, how? I put under comment line(remove) field «Country CityCountry» , and left only making «int IdofCountry» where i will remember just Id, and when i need to write it, i will use ViewModel , or something like that.
IF ANYONE HAS BETTER SOLUTION, PLEASE EXPLAIN IT. I dont like this solution but since it works ..
Anyone knows what i did wrong, and what is solution ?! Thanks!
public class Country { [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Name { get; set; } public virtual IEnumerable<City> CitiesinCountry { get; set; } } public class City { [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Name { get; set; } //public Country CityCountry { get; set; } <----FIX //[System.ComponentModel.DataAnnotations.Schema.ForeignKey("CityCountry")] <----FIX public int IdofCountry { get; set; } } public class VShContextClass : DbContext { public VShContextClass() { } public VShContextClass(DbContextOptions<VShContextClass> options) : base(options) { } public DbSet<Country> Country { get; set; } public DbSet<City> City { get; set; } } //controller public IActionResult CreateCity() { return View(); } [HttpPost] public IActionResult CreateCity(CityViewModel City) { if (ModelState.IsValid) { City newCity = new City() { Name = City.Name, IdofCountry = City.CountryId }; _repository.AddCity(newCity); } ModelState.Clear(); return View(); } //repository public void AddCity(VinylShop.Models.Record.City newCity) { db.City.Add(newCity); db.SaveChanges(); //----> THROWS EXCEPTION HERE }
So i guess you see in code where it throws exception:
Microsoft.EntityFrameworkCore.DbUpdateException HResult=0x80131500 Message=An error occurred while updating the entries. See the inner exception for details. Source=Microsoft.EntityFrameworkCore.Relational StackTrace: at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 parameters) at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func
3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func
2 operation) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList
1 entries) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges() at VinylShop.Repository.ShopRepo.AdministratorRepo.AddCity(City newCity) in C:UsersBobejnDesktopMyProject-CoreVinylShopVinylShopRepositoryShopRepoAdministratorRepo.cs:line 61 at VinylShop.Controllers.Administrator.AdminController.CreateCity(CityViewModel City) in C:UsersBobejnDesktopMyProject-CoreVinylShopVinylShopControllersAdministratorAdminController.cs:line 83 at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext() Inner Exception 1: SqlException: Invalid column name ‘CountryId’.
Further technical details
EF Core version: 2.0.6
Database Provider: Microsoft.EntityFrameworkCore.SqlServer Version=»2.0.2″
Operating system: Windows 10
IDE: Visual Studio 2017 15.4
Содержание
- Microsoft.EntityFrameworkCore.DbUpdateException HResult=0x80131500 Message=An error occurred while updating the entries. #12127
- Comments
- Anyone knows what i did wrong, and what is solution ?! Thanks!
- Further technical details
- An error occurred while updating the entries see the inner exception
- Answers
- An error occurred while updating the entries see the inner exception
- Answers
- An error occurred while updating the entries see the inner exception
- Answered by:
- Question
- Answers
- How to resolve another “An error occurred while updating the entries” exception in Entity Framework Core
- Problem
- Reason
- Solution
- Posts Related to «How to resolve another «An error occurred while updating the entries» exception in Entity Framework Core»:
- Search this site!
- About the site and the author
- Solutions are worthless unless shared!
- Want the latest tips directly to your inbox?
Microsoft.EntityFrameworkCore.DbUpdateException HResult=0x80131500 Message=An error occurred while updating the entries. #12127
Microsoft.EntityFrameworkCore.DbUpdateException HResult=0x80131500 Message=An error occurred while updating the entries. See the inner exception for details.
The INSERT statement conflicted with the FOREIGN KEY constraint «FK_City_Country_IdofCountry». The conflict occurred in database «MyVinylProject», table «dbo.Country», column ‘Id’.
The statement has been terminated.
-whole exception code is under code
UPDATE: Well, i fixed this with ViewModels, how? I put under comment line(remove) field «Country CityCountry» , and left only making «int IdofCountry» where i will remember just Id, and when i need to write it, i will use ViewModel , or something like that.
IF ANYONE HAS BETTER SOLUTION, PLEASE EXPLAIN IT. I dont like this solution but since it works ..
Anyone knows what i did wrong, and what is solution ?! Thanks!
So i guess you see in code where it throws exception:
Microsoft.EntityFrameworkCore.DbUpdateException HResult=0x80131500 Message=An error occurred while updating the entries. See the inner exception for details. Source=Microsoft.EntityFrameworkCore.Relational StackTrace: at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple 2 parameters) at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func 3 operation, Func 3 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func 2 operation) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable 1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList 1 entries) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges() at VinylShop.Repository.ShopRepo.AdministratorRepo.AddCity(City newCity) in C:UsersBobejnDesktopMyProject-CoreVinylShopVinylShopRepositoryShopRepoAdministratorRepo.cs:line 61 at VinylShop.Controllers.Administrator.AdminController.CreateCity(CityViewModel City) in C:UsersBobejnDesktopMyProject-CoreVinylShopVinylShopControllersAdministratorAdminController.cs:line 83 at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext() Inner Exception 1: SqlException: Invalid column name ‘CountryId’.
Further technical details
EF Core version: 2.0.6
Database Provider: Microsoft.EntityFrameworkCore.SqlServer Version=»2.0.2″
Operating system: Windows 10
IDE: Visual Studio 2017 15.4
The text was updated successfully, but these errors were encountered:
Источник
An error occurred while updating the entries see the inner exception
I followed this tutorial and wrote the following code:
I then get the following error:
An error occurred while updating the entries. See the inner exception for details.
The inner exception says the following:
Default values not supported
What am I doing wrong?
Thanks for your help!
Answers
I’m not sure why you don’t have execute SQL , maybe it’s because you aren’t connected to the database file. Go to your database explorer and see if you can create a connection to your database file.
But long term I would recommend you install sql server management studio (SSMS), it’s very useful for connecting to a sql server or sql server CE database and being able to run queries on it and view the database objects. The VS interface for working with databases isn’t very good.
One thing I noticed is the auto generated code by entity framework doesn’t create an identity column on your People table. You probably want to do that. So change the create statement code that’s in your window to this:
Larcolais Gong’s database script also shows this. However Larcolais’s code is for full sql server, I don’t know if it will work with your sql ce database. I think you just need to modify your script and include the identity keyword like above.
Let me know if this works. Seems like your code is working when Larcolais and myself try it, as long as there is a valid database and identity column in the table.
Источник
An error occurred while updating the entries see the inner exception
I followed this tutorial and wrote the following code:
I then get the following error:
An error occurred while updating the entries. See the inner exception for details.
The inner exception says the following:
Default values not supported
What am I doing wrong?
Thanks for your help!
Answers
I’m not sure why you don’t have execute SQL , maybe it’s because you aren’t connected to the database file. Go to your database explorer and see if you can create a connection to your database file.
But long term I would recommend you install sql server management studio (SSMS), it’s very useful for connecting to a sql server or sql server CE database and being able to run queries on it and view the database objects. The VS interface for working with databases isn’t very good.
One thing I noticed is the auto generated code by entity framework doesn’t create an identity column on your People table. You probably want to do that. So change the create statement code that’s in your window to this:
Larcolais Gong’s database script also shows this. However Larcolais’s code is for full sql server, I don’t know if it will work with your sql ce database. I think you just need to modify your script and include the identity keyword like above.
Let me know if this works. Seems like your code is working when Larcolais and myself try it, as long as there is a valid database and identity column in the table.
Источник
An error occurred while updating the entries see the inner exception
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
Am having this error when calling SaveChanges() : An error occurred while updating the entries. See the inner exception
for details. when use sql server profiler to inspect the query I found that Entity framework is trying to insert a value in column set as Identity in the concerned table.
How can prevent Entity framework from inserting in that field?
Answers
Here you have a link explaining this attribute:
The explanation was for Oracle providers, but the idea is the same for SQL Server.
Basically, with this attribute you say to EF that this field must set its values from its corresponding database identity value.
Please remember to Vote & «Mark As Answer» if this post is helpful to you.
Por favor, recuerda Votar y «Marcar como respuesta» si la solución de esta pregunta te ha sido útil.
Источник
How to resolve another “An error occurred while updating the entries” exception in Entity Framework Core
This post was most recently updated on June 23rd, 2022.
This article offers yet another possible fix to an issue, where trying to call SaveChanges() in Entity Framework Core throws a pretty generic “An error occurred while updating the entries”-exception, and you’re left wondering what in tarnation is wrong this time.
And admittedly, that’s a really generic error, so it could pretty much be whatever. But in this article, I’ll go through one possibility – hopefully, it helps!
Problem
Table of Contents
So I was just pushing in some new rows to an incredibly simple table in my small Azure MS SQL database when this error occurred:
Reason
Huh, so the actual error message itself is extremely generic. That’s not going to be enough to help us figure this out.
The error itself doesn’t help you much. But what about the HResult, it’s bound to contain an error code, right?
Well, yes. The HResults were:
- Exception: -2146233088 (Generic, doesn’t help us much)
- InnerException: -2146232060 (Generic SQL Server error)
Ugh – that’s extremely generic as well! No help at all.
But wait – let’s do what it tells us to, and see the inner exception, then:
That’s, uhh… Not that helpful, still? What’s up with all of these errors from other tables??
Oh. Wait. The exception only contains references to other tables, not about my actual entity at all? References are going to be the key term here.
Solution
Okay – this is going to be specific to this particular case, and probably different for you, but might be worth checking out anyway.
So, I was handling some non-tracked entities earlier in the code – and was in fact trying to associate one of these entities with a new entity that I was saving.
In the code, this looks somewhat like the below:
Did you catch it? The item is not tracked – and you can’t associate it with a tracked entity!
So, what you need to do, is to fetch the item without.AsNoTracking() if you plan on associating it with any tracked entities.
Super simple – but the exception thrown is definitely not very informative.
In case this article didn’t help you, I have another one explaining another solution to the same error (but a different underlying issue) here:
Antti Koskela is a proud digital native nomadic millennial full stack developer (is that enough funny buzzwords? That’s definitely enough funny buzzwords!), who works as Solutions Architect for Precio Fishbone, building delightful Digital Workplaces.
He’s been a developer from 2004 (starting with PHP and Java), and he’s been working on .NET projects, Azure, Office 365, SharePoint and a lot of other stuff. He’s also Microsoft MVP for Office Development.
This is his personal professional (e.g. professional, but definitely personal) blog.
- How to export the SSL/TLS certificate from a website using PowerShell? — January 10, 2023
- 2022 Year Review – Stop Caring & Just Enjoy The Ride! — January 3, 2023
- How to replace the default fake “ACME” certificate for Kubernetes/AKS? — December 27, 2022
Search this site!
Welcome! You just stumbled upon the home page of an all-around artisan code crafter and Microsoft MVP, Antti «koskila» Koskela.
Don’t hesitate to leave comments. I read them all and try to reply as well!
More information about me in the About -section!
Solutions are worthless unless shared!
Check out the tech & programming tips, often about ASP.NET MVC, Entity Framework, Microsoft SharePoint Server & Online, Azure, Active Directory, Office 365 or other parts of the ever-growing and more and more intimidating stack that Microsoft offers us.
I’ve been developing both classic server stuff, but also (and actually especially) more cloud-oriented stuff in the past 15 years.
There’s an occasional post about software issues other than on Microsoft’s stack, and a rare post about hardware, too! And sometimes I might post about my sessions at different community events, or experiences as an expat living in a foreign country (in 2017, that country was the USA, in 2018 & 2019 Canada).
And since I’m hosting this site on WordPress, and boy does WordPress experience a lot of issues, I might also post something about solving those cases. Like PHP compatibility issues.
Want the latest tips directly to your inbox?
Like these posts and tips? You can get them automatically right as I post them! Enter your email here or check out the RSS feed here: https://www.koskila.net/feed/
And no worries — it’s just notifications of new posts coming in, nothing else 🙂
Источник
- Remove From My Forums
-
Question
-
I am seeing this error frequently. System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. —> System.Data.SqlClient.SqlException:
String or binary data would be truncated.
The statement has been terminated.
We dont use store procs but use a lot of Entity Framework . Not sure where the update is erroring out when its trying to save. Is there a way to know which table its failing at and to which column?Thanks
-
Moved by
Tuesday, March 22, 2016 8:41 PM
Better answer can be here
-
Moved by
Answers
-
The only thing I can suggest is to try capturing that particular error and write a log file with the statement and all the passed values. In other words, this will require changing application code and writing code for that specific error.
-
Marked as answer by
Eric__Zhang
Wednesday, April 6, 2016 8:53 AM
-
Marked as answer by
olegall 0 / 0 / 0 Регистрация: 27.01.2014 Сообщений: 116 |
||||
1 |
||||
18.10.2016, 15:47. Показов 22941. Ответов 6 Метки нет (Все метки)
Пытаюсь сохранить объект в БД:
получаю исключение: An exception of type ‘System.Data.Entity.Infrastructure.DbUpdateExcepti on’ occurred in EntityFramework.dll but was not handled in user code на методе SaveChanges Additional information: An error occurred while updating the entries. See the inner exception for details. все поля модели и таблицы БД соответствуют друг другу (типы, их число и названия), делал повторно миграцию — всё чисто.
__________________
0 |
783 / 615 / 272 Регистрация: 04.08.2015 Сообщений: 1,707 |
|
18.10.2016, 17:32 |
2 |
dbContext.Entry(entity).State = System.Data.Entity.EntityState.Added; Какой смысл одному свойству дважды присваивать значение? Останется то, что во 2-й строке.
0 |
0 / 0 / 0 Регистрация: 27.01.2014 Сообщений: 116 |
|
18.10.2016, 18:29 [ТС] |
3 |
строки 6,7,8 я поочерёдно комментировал в разных комбинациях
0 |
91 / 90 / 37 Регистрация: 05.08.2011 Сообщений: 428 |
|
18.10.2016, 19:05 |
4 |
olegall, комментируйте разом. 6,7,8 строки. Где-то до этого в коде отключаете авто детект изменений?
See the inner exception for details. Вы смотрели? Что там написано?
0 |
olegall 0 / 0 / 0 Регистрация: 27.01.2014 Сообщений: 116 |
||||
19.10.2016, 09:27 [ТС] |
5 |
|||
Где-то до этого в коде отключаете авто детект изменений? — это не понял. я ничего подобного вроде не делал Inner exception: Invalid object name ‘dbo.EntityModels’. — видимо означает попытка обращения к таблице в БД EntityModels. Но такой таблицы нет (есть Entities). Причём я помню что такая таблица как-то появлялась, и я её удалял. Возможно эта инфо сохранилась в кеше или ещё где-то. Поиск в проекте по строке «dbo.EntityModels» ничего не дал Добавлено через 6 минут
Добавлено через 16 минут
0 |
lvlkoo .NET C#,ASP.NET MVC 592 / 503 / 225 Регистрация: 16.10.2010 Сообщений: 1,902 |
||||
19.10.2016, 17:07 |
6 |
|||
olegall, название таблицы определяется не названием свойства в контексте, а названием сущности. То есть если у вас сущность называется EntityModels, то и таблица будет называться EntityModels. Название табицы можно указать явно, с помощью атрибута Table(name);
А лучше просто переименуйте сущность EntityModels в Entities
0 |
olegall 0 / 0 / 0 Регистрация: 27.01.2014 Сообщений: 116 |
||||
20.10.2016, 11:03 [ТС] |
7 |
|||
Сделал так
при выполнении миграций (команда Update-Database) возникает ошибка Пробовал переименовать таблицу Entities, но новая таблица не создаётся. Не знаю что делать
0 |
Hello everybody,I got an error when I was trying to updating the data in the database in my 1st ASP.Net MVC application and the error is «
An error occurred while updating the entries. See the InnerException for details.
So please help me to solve out my this problem.Here’s below is the code:
public ActionResult Create() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([Bind(Exclude="Id")] Movie movieToCreate) { if (!ModelState.IsValid) return View(); _db.AddToMovies(movieToCreate); _db.SaveChanges(); //Error Line return RedirectToAction(movieToCreate); }
If you have any DateTime property in Movie class please initialize with current DateTime like below before save
movieToCreate.DateProperty=DateTime.Now; _db.AddToMovies(movieToCreate); _db.SaveChanges();
Hope this helps
please check all column there have some column not allow null.
In my case column [ID] not allow null, so you need to give value for it.
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900