An error occurred while updating the entries ошибка

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 (…)

enter image description here

(…) Having this Method Overriding will avoid creating tables with pluralized names. Now it will create a Table called “PhoneNumber” , Not “PhoneNumbers” (…)

Почему не добавляются записи в базу данных?

К экзамену решил изучить разработку приложения на C# и SQLServer. Нашел очень интересный гайд https://nationalteam.worldskills.ru/skills/program…. Делаю все шаг за шагом, но на этапе добавления записи из интерфейса программы получаю исключение

An error occurred while updating the entries. See the inner exception for details.

, хотя если добавить записи напрямую через SQLServer и потом отредактировать, то изменения вносятся без проблем. Схема БД:
62588e76e302e010111257.png


  • Вопрос задан

    более года назад

  • 240 просмотров

используйте студию и разворачивайте все сообщения, в конце концов у вас будет точка ошибки и там уже разберетесь

Пригласить эксперта

У ENTITY FRAMEWORK есть свой взгляд на то, что такое первичный ключ. Возможно использование вами составных ключей в промежуточных таблицах не даёт провести обновления.


  • Показать ещё
    Загружается…

08 июн. 2023, в 22:08

50000 руб./за проект

08 июн. 2023, в 22:01

3000 руб./за проект

08 июн. 2023, в 21:41

10000 руб./за проект

Минуточку внимания

  • Remove From My Forums
  • Question

  • I have a super-simple screen that has one entity an a grid (that used to work).  If I try to save, using the built-in button, I get:

    «An error occurred while updating the entries. See the inner exception for details.»

    It only happens in my published Azure cloud service (not on my local machine).  I have not been able to figure out how to get the Inner Exception.  I enabled the «Enable Created/Modified Properties» and I think that it might have something
    to do with that.  I unchecked it and the problem still exists.

    I have not been able to get tracing to work (I have a separate question going on that issue) so I am trying to figure out how to get the actual error.  Any ideas on how to get the actual error would be appreciated.

    Thanks,

    Mark

Answers

  • Otis:

    I think the error was thrown by the code in the catch block because the InnerException is null.

    Yesterday, I published to Azure using a database name which did not exist.  This caused LightSwitch to create a new database which should be perfect.  Then I used the Azure migration wizard to copy data from my old database to the new one. 
    I have done this before several times and it has always worked.

    I was really expecting this to fix the problem, but it did not. 

    I finally figured it out: I had some validation code on the Client table. When I commented this out, the error went away.  This code used to work, but for some reason it is causing the error.

    The really annoying thing is that I could never get a helpful error message and I spent a lot of time trying to figure this out.

    Thanks again for your help.

    Mark

    • Marked as answer by

      Friday, August 29, 2014 1:32 PM

This post was most recently updated on February 19th, 2023.

3 min read.

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

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:

An error occurred while updating the entries. See the inner exception for details.

This error can be thrown due to incredibly many different reasons. And there are different variants of the error – some of them below:

microsoft.entityframeworkcore.dbupdateexception: 'an error occurred while updating the entries. see the inner exception for details.
microsoft.entityframeworkcore.dbupdateexception: 'an error occurred while saving the entity changes. see the inner exception for details.'

What gives? 🤔

Reason

Huh, so the actual error message itself is extremely generic. That’s not going to be enough to help us figure this out.

But what about the details of the exception – you can catch it and, like the error proposes, take a look at the inner exception and associated 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:

{"Cannot insert explicit value for identity column in table '[Not the table I was inserting stuff to, and not one that had any direct relations to it either]' when IDENTITY_INSERT is set to OFF.rnCannot insert explicit value for identity column in table '[Another unrelated table]' when IDENTITY_INSERT is set to OFF.rnCannot insert explicit value for identity column in table '[One more unrelated table]' when IDENTITY_INSERT is set to OFF.rnCannot insert explicit value for identity column in table '[Yet another unrelated table]' when IDENTITY_INSERT is set to OFF.rnCannot insert explicit value for identity column in table '[This one was just as unrelated]' when IDENTITY_INSERT is set to OFF."}

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? And that’s going to be pretty important.

See – those 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:

var item = ctx.Entities.Where(x => x.Amount > 1000).AsNoTracking().First();

ctx.OtherEntities.Add(new OtherEntity(){
   Id = 0,
   Entity = item
});

ctx.SaveChanges();

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, your underlying cause might be different. But luckily, I have another one explaining another solution to the same error (but a different underlying issue) here:

  • Author
  • Recent Posts

mm

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 Azure.

This is his personal professional (e.g. professional, but definitely personal) blog.

mm

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 Azure.

This is his personal professional (e.g. professional, but definitely personal) blog.

mm

4.5
2
votes

Article Rating

In this guide, we will walk you through the steps to troubleshoot and fix the ‘An Error Occurred While Updating the Entries’ error in your application. This error is commonly encountered when working with Entity Framework or other database-related operations in .NET applications.

Table of Contents

  1. Understanding the Error
  2. Investigating the Inner Exception
  3. Common Causes and Solutions
  4. FAQ
  5. Related Links

Understanding the Error

This error occurs when an exception is thrown during a database operation, such as inserting, updating, or deleting records. The error message is quite generic and does not provide much information about the root cause.

To better understand the issue, you must dig deeper into the exception details, specifically the inner exception. The inner exception contains more specific information about the actual problem that occurred during the database operation.

Investigating the Inner Exception

To obtain the inner exception details, follow these steps:

  1. Catch the exception: Add a try-catch block around the database operation that is causing the error. This will allow you to catch the exception thrown by the Entity Framework.
try
{
    // Perform the database operation
}
catch (Exception ex)
{
    // Handle the exception
}
  1. Log the inner exception: Inside the catch block, log the inner exception details to a file, console, or any other logging mechanism that you are using in your application. This will help you identify the root cause of the error.
try
{
    // Perform the database operation
}
catch (Exception ex)
{
    Console.WriteLine("Error: " + ex.Message);
    Console.WriteLine("Inner Exception: " + ex.InnerException?.Message);
}
  1. Analyze the inner exception: Once you have logged the inner exception details, analyze them to identify the actual problem.

Common Causes and Solutions

Here are some common causes for the ‘An Error Occurred While Updating the Entries’ error and their solutions:

Cause 1: Database Connection Issues

Solution: Check your database connection string and ensure that it is correct. Verify if the credentials are valid and if the database server is running.

Cause 2: Foreign Key Constraint Violation

Solution: Ensure that the relationships between your tables are correctly configured and that you are not trying to insert or update records with invalid foreign key values.

Cause 3: Unique Constraint Violation

Solution: Make sure that you are not trying to insert or update records with duplicate values for columns that have a unique constraint.

Cause 4: Data Type Mismatch

Solution: Check if you are trying to insert or update records with incorrect data types. This might include passing a string value to an integer column or a date value to a string column.

Cause 5: Column or Table Not Found

Solution: Verify that the column and table names in your database match the ones used in your application. Check for typos or case sensitivity issues.

FAQ

1. How do I fix a foreign key constraint violation?

To fix a foreign key constraint violation, ensure that the relationships between your tables are correctly configured and that you are not trying to insert or update records with invalid foreign key values.

2. How can I resolve a unique constraint violation?

To resolve a unique constraint violation, make sure that you are not trying to insert or update records with duplicate values for columns that have a unique constraint.

3. What should I do if there is a data type mismatch?

In case of a data type mismatch, check if you are trying to insert or update records with incorrect data types. This might include passing a string value to an integer column or a date value to a string column. Correct the data types and try the operation again.

4. How do I handle column or table not found errors?

To handle column or table not found errors, verify that the column and table names in your database match the ones used in your application. Check for typos or case sensitivity issues.

5. Can I prevent ‘An Error Occurred While Updating the Entries’ errors by using a different ORM?

While using a different ORM might help in some cases, it is important to understand the root cause of the error, as it could be related to database or application configuration issues rather than the ORM itself.

  • Entity Framework Core: Logging and Diagnostics
  • Entity Framework 6: Logging and Intercepting Database Operations

olegall

0 / 0 / 0

Регистрация: 27.01.2014

Сообщений: 116

1

18.10.2016, 15:47. Показов 25142. Ответов 6

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Пытаюсь сохранить объект в БД:

C#
1
2
3
4
5
6
7
8
9
10
      public void Add(EntityModels entity)
        {
            //dbContext.Database.ExecuteSqlCommand("INSERT INTO dbo.Entities (CategoryId, Applicability, Number, Name, Engineer, Text, PathToPDF, PathToImage) VALUES ('" + entity.CategoryId + "', '" + entity.Applicability + "', '" + entity.Number + "', '" + entity.Name + "', '" + entity.Engineer + "', '" + entity.Text + "', '" + entity.PathToPDF + "', '" + entity.PathToImage + "')");
            //entity.PathToPDF = "";
            dbContext.Entities.Add(entity);
            dbContext.Entry(entity).State = System.Data.Entity.EntityState.Added;
            dbContext.Entry(entity).State = System.Data.Entity.EntityState.Modified;
            dbContext.Configuration.AutoDetectChangesEnabled = true;
            dbContext.SaveChanges();
        }

получаю исключение:

An exception of type ‘System.Data.Entity.Infrastructure.DbUpdateException’ 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.

все поля модели и таблицы БД соответствуют друг другу (типы, их число и названия), делал повторно миграцию — всё чисто.
NULL-в сохраняемых данных нет.
Причём занесение данных через прямой sql запрос (1-я закомментированная строка) проходит корректно. Эксперименторивал с комбинациями строк 3,4,5 метода. Гуглил — не помогло. Как отлаживать такие ошибки?



0



783 / 615 / 272

Регистрация: 04.08.2015

Сообщений: 1,707

18.10.2016, 17:32

2

Цитата
Сообщение от olegall
Посмотреть сообщение

dbContext.Entry(entity).State = System.Data.Entity.EntityState.Added;
dbContext.Entry(entity).State = System.Data.Entity.EntityState.Modified;

Какой смысл одному свойству дважды присваивать значение? Останется то, что во 2-й строке.
Вангую, что вы новую запись принудительно объявляете модифицированной. После этого вместо Insert пытается выполниться Update, который не проходит.



0



0 / 0 / 0

Регистрация: 27.01.2014

Сообщений: 116

18.10.2016, 18:29

 [ТС]

3

строки 6,7,8 я поочерёдно комментировал в разных комбинациях
Added не проходит



0



91 / 90 / 37

Регистрация: 05.08.2011

Сообщений: 428

18.10.2016, 19:05

4

olegall, комментируйте разом. 6,7,8 строки. Где-то до этого в коде отключаете авто детект изменений?
Для чего, сначала добавляете сущность (5 строка), стандартно она будет помечена добавленной, затем помечаете её добавленной (6 строка), затем обновленной (7 строка), потом включаете детект изменений (8 строка). Последнее вообще не понятно для чего.
+ в сообщении ошибки указано:

Цитата
Сообщение от olegall
Посмотреть сообщение

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 минут
Контекст:

C#
1
2
3
4
5
6
7
namespace Engine.Models
{
    public class EntityContext : DbContext
    {
        public DbSet<EntityModels> Entities { get; set; }
    }
}

Добавлено через 16 минут
UPD:
я создал таблицу EntityModels — клон Entities — и исключение пропало. Как теперь избавить проект от информации о таблице
EntityModels? Я удалял папку migrations, создал миграцию заново — не помогло



0



lvlkoo

.NET C#,ASP.NET MVC

Эксперт .NET

593 / 504 / 225

Регистрация: 16.10.2010

Сообщений: 1,902

19.10.2016, 17:07

6

olegall, название таблицы определяется не названием свойства в контексте, а названием сущности.

То есть если у вас сущность называется EntityModels, то и таблица будет называться EntityModels.

Название табицы можно указать явно, с помощью атрибута Table(name);

C#
1
2
3
4
5
[Table("Entities")]
class EntityModels
{
    .....
}

А лучше просто переименуйте сущность EntityModels в Entities



0



olegall

0 / 0 / 0

Регистрация: 27.01.2014

Сообщений: 116

20.10.2016, 11:03

 [ТС]

7

Сделал так

C#
1
2
3
4
5
[Table("Entities")]
class EntityModels
{
    .....
}

при выполнении миграций (команда Update-Database) возникает ошибка
Either the parameter @objname is ambiguous or the claimed @objtype (OBJECT) is wrong

Пробовал переименовать таблицу Entities, но новая таблица не создаётся. Не знаю что делать



0



By default, the .Net client has a 30-second client-side command timeout. The error you are seeing is saying that the response from the server took more than 30 seconds.

Here’s some example C# code showing the problem by executing a WAITFOR DELAY statement that waits 31 seconds:

using System;
using System.Data.SqlClient;

namespace ConnectionTimeoutTest
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnectionStringBuilder sqlConnectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder
            {
                InitialCatalog = "tempdb",
                IntegratedSecurity = true,
                DataSource = "localhost"
            };

            using SqlConnection connection = new SqlConnection();
            connection.ConnectionString = sqlConnectionStringBuilder.ConnectionString;
            connection.Open();
            using SqlCommand sqlCommand = new SqlCommand("WAITFOR DELAY '00:00:31';SELECT 'Hello World!';", connection);
            SqlDataReader reader = sqlCommand.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(reader.GetString(0));
            };
        }
    }
}

And the exception:

System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Source=Core .Net SqlClient Data Provider

StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
at ConnectionTimeoutTest.Program.Main(String[] args) in C:UsersHannah.MVCTsourcereposConnectionTimeoutTestConnectionTimeoutTestProgram.cs:line 23

Inner Exception 1:
Win32Exception: The wait operation timed out.

Here’s the fix to make the client wait for 60 seconds:

using System;
using System.Data.SqlClient;

namespace ConnectionTimeoutTest
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnectionStringBuilder sqlConnectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder
            {
                InitialCatalog = "tempdb",
                IntegratedSecurity = true,
                DataSource = "localhost"
            };

            using SqlConnection connection = new SqlConnection();
            connection.ConnectionString = sqlConnectionStringBuilder.ConnectionString;
            connection.Open();
            using SqlCommand sqlCommand = new SqlCommand("WAITFOR DELAY '00:00:31';SELECT 'Hello World!';", connection);
            sqlCommand.CommandTimeout = 60;  // <---- this is new
            SqlDataReader reader = sqlCommand.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine(reader.GetString(0));
            };
        }
    }
}

The code above is available in GitHub.

Hi Folks,

I’m getting the following error message when I try to save a new record to the Visits table:

System.Data.Entity.Infrastructure.DbUpdateException
  HResult=0x80131501
  Message=An error occurred while updating the entries. See the inner exception for details.
  Source=EntityFramework
  StackTrace:
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at LabEle3._Default.Page_Load(Object sender, EventArgs e) in C:UsersRobDocumentsVisual Studio 2013ProjectsLabEle3LabEle3Default.aspx.vb:line 89

Inner Exception 1:
UpdateException: An error occurred while updating the entries. See the inner exception for details.

Inner Exception 2:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint «FK_dbo.Visits_dbo.Visitors_VisitorId». The conflict occurred in database «C:USERSROBDOCUMENTSVISUAL STUDIO 2013PROJECTSLABELE3LABELE3APP_DATALABELE3.MDF»,
table «dbo.Visitors», column ‘VisitorId’.
The statement has been terminated.

Here is my table T-SQL:

Visits table:

CREATE TABLE [dbo].[Visits] (
    [VisitId]          INT      IDENTITY (1, 1) NOT NULL,
    [VisitorId]        INT      NOT NULL,
    [VisitDateAndTime] DATETIME NULL,
    CONSTRAINT [PK_dbo.Visits] PRIMARY KEY CLUSTERED ([VisitId] ASC),
    CONSTRAINT [FK_dbo.Visits_dbo.Visitors_VisitorId] FOREIGN KEY ([VisitorId]) REFERENCES [dbo].[Visitors] ([VisitorId]) ON DELETE CASCADE
);

GO
CREATE NONCLUSTERED INDEX [IX_VisitorId]
    ON [dbo].[Visits]([VisitId] ASC);

Visitors table:

CREATE TABLE [dbo].[Visitors] (
    [VisitorId]   INT            IDENTITY (1, 1) NOT NULL,
    [IPaddress]   NVARCHAR (MAX) NULL,
    [IPlong]      INT            NULL,
    [DateAndTime] DATETIME       NULL,
    [Visits]      INT            DEFAULT ((1)) NOT NULL,
    CONSTRAINT [PK_dbo.Visitors] PRIMARY KEY CLUSTERED ([VisitorId] ASC)
);

GO
CREATE NONCLUSTERED INDEX [IX_IPlong]
    ON [dbo].[Visitors]([IPlong] ASC);

Here are my class definitions:

Visit class:

Public Class Visit
    Public Property VisitId() As Integer
    Public Property VisitorId() As Integer
    Public Property VisitDateAndTime() As Date
End Class

VisitContext class:

Imports System.Data.Entity

Public Class VisitContext
    Inherits DbContext
    Public Sub New()
        MyBase.New(«LabEle3»)
    End Sub
    Public Property Visits As DbSet(Of Visit)
End Class

I first make a Visitor record and it successfully saves. Then I make a new Visit record using the integer value ThisVisitorId from the Visitor record for the VisitorId field:

            ‘make new visit
            Dim VisitDb As New VisitContext
            Dim VisitorVisit As New Visit
            VisitorVisit.VisitDateAndTime = Now
            VisitorVisit.VisitorId = ThisVisitorId

            VisitDb.Visits.Add(VisitorVisit)

When I try to save the Visit record on the line VisitDb.SaveChanges(), I get the error.

‘save new visit record
Try
    VisitDb.SaveChanges()
Catch ex As DbEntityValidationException
    For Each a In ex.EntityValidationErrors
        For Each b In a.ValidationErrors
        Dim st1 As String = b.PropertyName
        Dim st2 As String = b.ErrorMessage
        Debug.WriteLine(st1)
        Debug.WriteLine(st2)
        Next
    Next
End Try

I don’t understand why there is a conflict between the VisitorId field and the Foreign Key: they are the same value!

Any help would be appreciated.

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, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func2 operation) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList1 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

Понравилась статья? Поделить с друзьями:
  • An error has occurred 3ds max ошибка
  • An brake light ошибки в ситроен
  • Amxbans main amxx amxbans ошибка при соединении
  • Amp error pioneer что делать ошибка
  • Among us что делать если ошибка в игре