An error occurred while saving the entity changes see the inner exception for details

After upgrading to .net6.0 version while saving 10 digit decimal value - for example - 1234567890.12345, this error occurs: OverflowException: Conversion overflows Please suggest how to fix this ...

By default in EF Core (and previous versions), if you have not specified the precision of a Decimal typed column in the EF model, then it will default to a precision of 18 digits and 2 decimal places, (18,2).

Most likely in EF6 you had a convention to define all decimals as DECIMAL(35,17)

In .Net 6 there is support for conventions again, we now add this to the DbContext:

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    // Decimal (37,12) convention
    configurationBuilder.Properties<decimal>()
        .HavePrecision(37, 12);
}

based on solution from Loop/reflect through all properties in all EF Models to set Column Type


EF Core didn’t support the same model for configuration conventions as EF6 OOTB, it sucked for a time, but we moved on, here is an old discussion on the topic: Where are Entity Framework Core conventions? also have a read here for

One of the benefits to this is that the model configuration is the standard place for this type of logic, so by keeping the config in-line, or atleast within your DbContext project your conventions are now more discoverable. In EF6 many of us implemented custom conventions and packaged them in distributable libraries for re-use. This effectively made them black-boxes which would often result in local variants of the same conventions so that the current project developers had access to the logic when they needed to inspect it or change it.

@csmager I can’t reproduce this—see my code below. Please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

@AndriySvyryd With the code below I get the following model and change tracker state. The update pipeline then attempts to insert null. Any idea what is happening here?

Model: 
  EntityType: Foo
    Properties: 
      Id (int) Required PK FK Index AfterSave:Throw ValueGenerated.OnAdd
      CurrentPeriodNumber (int?) FK Index
    Navigations: 
      CurrentPeriod (FooPeriod) ToPrincipal FooPeriod
      Periods (ICollection<FooPeriod>) Collection ToDependent FooPeriod Inverse: Foo
    Keys: 
      Id PK
    Foreign keys: 
      Foo {'Id', 'CurrentPeriodNumber'} -> FooPeriod {'FooId', 'PeriodNumber'} Unique ToPrincipal: CurrentPeriod ClientSetNull
    Indexes: 
      Id, CurrentPeriodNumber  Unique
  EntityType: FooPeriod
    Properties: 
      FooId (int) Required PK FK AfterSave:Throw
      PeriodNumber (int) Required PK AfterSave:Throw
    Navigations: 
      Foo (Foo) ToPrincipal Foo Inverse: Periods
    Keys: 
      FooId, PeriodNumber PK
    Foreign keys: 
      FooPeriod {'FooId'} -> Foo {'Id'} ToDependent: Periods ToPrincipal: Foo Cascade
Foo {Id: 0} Added
  Id: 0 PK FK
  CurrentPeriodNumber: <null> FK
  CurrentPeriod: <null>
  Periods: [{FooId: 0, PeriodNumber: 1}]
FooPeriod {FooId: 0, PeriodNumber: 1} Added
  FooId: 0 PK FK
  PeriodNumber: 1 PK
  Foo: {Id: 0}
#nullable enable

public class Foo
{
    public int Id { get; set; }
    public int? CurrentPeriodNumber { get; set; }
    public FooPeriod? CurrentPeriod { get; set; }
    public ICollection<FooPeriod> Periods { get; } = new HashSet<FooPeriod>();
}

public class FooPeriod
{
    public int FooId { get; set; }
    public int PeriodNumber { get; set; }
    public Foo? Foo { get; set; }
}

public class SomeDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(Your.ConnectionString)
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Foo>(entity =>
        {
            entity.HasKey(x => x.Id);
            entity.Property(x => x.Id)
                .ValueGeneratedOnAdd();
            entity.HasOne(x => x.CurrentPeriod)
                .WithOne()
                .HasForeignKey<Foo>(x => new { x.Id, x.CurrentPeriodNumber });
        });

        modelBuilder.Entity<FooPeriod>(entity =>
        {
            entity.HasKey(x => new { x.FooId, x.PeriodNumber });
            entity.HasOne(x => x.Foo)
                .WithMany(x => x.Periods)
                .HasForeignKey(x => x.FooId);
        });
    }
}

public class Program
{
    public static void Main()
    {
        using (var context = new SomeDbContext())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            var period = new FooPeriod
            {
                PeriodNumber = 1,
                Foo = new Foo()
            };

            context.Add(period);
            context.SaveChanges();
        }
    }
}
fail: 2/21/2022 11:56:46.224 RelationalEventId.CommandError[20102] (Microsoft.EntityFrameworkCore.Database.Command)
      Failed executing DbCommand (24ms) [Parameters=[@p0=NULL (DbType = Int32)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      DECLARE @inserted0 TABLE ([Id] int);
      INSERT INTO [Foo] ([CurrentPeriodNumber])
      OUTPUT INSERTED.[Id]
      INTO @inserted0
      VALUES (@p0);
      SELECT [i].[Id] FROM @inserted0 i;
fail: 2/21/2022 11:56:46.245 CoreEventId.SaveChangesFailed[10000] (Microsoft.EntityFrameworkCore.Update)
      An exception occurred in the database while saving changes for context type 'SomeDbContext'.
      Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
       ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Id', table 'SixOh.dbo.Foo'; column does not allow nulls. INSERT fails.
      The statement has been terminated.
         at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
         at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
         at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
         at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
         at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
         at System.Data.Common.DbCommand.ExecuteReader()
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
         at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
      ClientConnectionId:1c4cbf7d-e825-4b2e-b16c-ccfe8932e760
      Error Number:515,State:2,Class:16
         --- End of inner exception stack trace ---
         at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
         at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
         at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
         at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
         at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)
         at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<>c.<SaveChanges>b__104_0(DbContext _, ValueTuple`2 t)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
         at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
         at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
Unhandled exception. Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Id', table 'SixOh.dbo.Foo'; column does not allow nulls. INSERT fails.
The statement has been terminated.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
ClientConnectionId:1c4cbf7d-e825-4b2e-b16c-ccfe8932e760
Error Number:515,State:2,Class:16
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<>c.<SaveChanges>b__104_0(DbContext _, ValueTuple`2 t)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
   at Program.Main() in C:localcodeAllTogetherNowSixOhProgram.cs:line 134

I cannot tell you how many times I’ve had the following conversation

“Hey I’m getting an error”

“What’s the error?”

“DBUpdateException”

“OK, what’s the message though, that could be anything”

“ahhh.. I didn’t see…..”

Frustratingly, When doing almost anything with Entity Framework including updates, deletes and inserts, if something goes wrong you’ll be left with the generic exception of :

Microsoft.EntityFrameworkCore.DbUpdateException: ‘An error occurred while saving the entity changes. See the inner exception for details.’

It can be extremely annoying if you’re wanting to catch a particular database exception (e.g. It’s to be expected that duplicates might be inserted), and handle them in a different way than something like being unable to connect to the database full stop. Let’s work up a quick example to illustrate what I mean.

Let’s assume I have a simple database model like so :

class BlogPost
{
    public int Id { get; set; }
    public string PostName { get; set; }
}

And I have configured my entity to have a unique constaint meaning that every BlogPost must have a unique name :

modelBuilder.Entity<BlogPost>()
    .HasIndex(x => x.PostName)
    .IsUnique();

If I do something as simple as :

context.Add(new BlogPost
{
    PostName = "Post 1"
});

context.Add(new BlogPost
{
    PostName = "Post 1"
});

context.SaveChanges();

The *full* exception would be along the lines of :

Microsoft.EntityFrameworkCore.DbUpdateException: ‘An error occurred while saving the entity changes. See the inner exception for details.’
Inner Exception
SqlException: Cannot insert duplicate key row in object ‘dbo.BlogPosts’ with unique index ‘IX_BlogPosts_PostName’. The duplicate key value is (Post 1).

Let’s say that we want to handle this exception in a very specific way, for us to do this we would have to have a bit of a messy try/catch statement :

try
{
    context.SaveChanges();
}catch(DbUpdateException exception) when (exception?.InnerException?.Message.Contains("Cannot insert duplicate key row in object") ?? false)
{
    //We know that the actual exception was a duplicate key row
}

Very ugly and there isn’t much reusability here. If we want to catch a similar exception elsewhere in our code, we’re going to be copy and pasting this long catch statement everywhere.

And that’s where I came across the EntityFrameworkCore.Exceptions library!

Using EntityFrameworkCore.Exceptions

The EntityFrameworkCore.Exceptions library is extremely easy to use and I’m actually somewhat surprised that it hasn’t made it’s way into the core EntityFramework libraries already.

To use it, all we have to do is run the following on our Package Manager Console :

Install-Package EntityFrameworkCore.Exceptions.SqlServer

And note that there are packages for things like Postgres and MySQL if that’s your thing!

Then with a single line for our DB Context we can set up better error handling :

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseExceptionProcessor();
}

If we run our example code from above, instead of our generic DbUpdateException we get :

EntityFramework.Exceptions.Common.UniqueConstraintException: ‘Unique constraint violation’

Meaning we can change our Try/Catch to be :

try
{
    context.SaveChanges();
}catch(UniqueConstraintException ex)
{
    //We know that the actual exception was a duplicate key row
}

Much cleaner, much tidier, and far more reusable!

RRS feed

  • Remove From My Forums
  • Question

  • Hi!

    I am creating an ASP.NET Web Form with Azure SQL Database, hosted by Azure. I created some tables in the database. I’ve added classes for each table in the «Models» folder. I also added «new scaffolded item», so it had automatically created
    each folders own forms. In the Insert.aspx.cs file the SaveChanges() method always gives an exception. Why? What should I do now?

    Thanks!

Answers

    • Marked as answer by
      Fred Bao
      Monday, December 29, 2014 9:06 AM

All replies

  • HTML:

    <div>
    <p>&nbsp;</p>
            <asp:FormView runat=»server»
                ItemType=»SchoolInTheCloud.Models.Library» DefaultMode=»Insert»
                InsertItemPosition=»FirstItem» InsertMethod=»InsertItem»
                OnItemCommand=»ItemCommand» RenderOuterTable=»false»>
                <InsertItemTemplate>
                    <fieldset class=»form-horizontal»>
    <legend>Insert Library</legend>
           <asp:ValidationSummary runat=»server» CssClass=»alert alert-danger» />
    <asp:DynamicControl Mode=»Insert» DataField=»FileName» runat=»server» />
    <asp:DynamicControl Mode=»Insert» DataField=»FilePath» runat=»server» />
                       
    <div class=»form-group»>
                           
    <div class=»col-sm-offset-2 col-sm-10″>
                              
    <asp:Button runat=»server» ID=»InsertButton» CommandName=»Insert» Text=»Insert» CssClass=»btn btn-primary» />
                               
    <asp:Button runat=»server» ID=»CancelButton» CommandName=»Cancel» Text=»Cancel» CausesValidation=»false» CssClass=»btn btn-default» />
                           
    </div>
    </div>
                    </fieldset>
                </InsertItemTemplate>
    </asp:FormView>
    </div>

    C#

    protected SchoolInTheCloud.Models.SITCContext _db = new SchoolInTheCloud.Models.SITCContext();

            protected void Page_Load(object sender, EventArgs e)
            {

            }

            // This is the Insert method to insert the entered Library item
            // USAGE: <asp:FormView InsertMethod=»InsertItem»>
            public void InsertItem()
            {
                using (_db)
                {
                    var item = new SchoolInTheCloud.Models.Library();

                    TryUpdateModel(item);

                    if (ModelState.IsValid)
                    {
                        // Save changes
                        _db.Libraries.Add(item);
                        _db.SaveChanges();

                        Response.Redirect(«Default»);
                    }
                }
            }

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

  • inner exception message: implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query.

    Please help. Thanks!;)

    • Marked as answer by
      Fred Bao
      Monday, December 29, 2014 9:06 AM

This post was most recently updated on June 23rd, 2022.

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

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.

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:

{"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? 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, 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 Office Development.

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

mm

4.5
2
votes

Article Rating

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

olegall

0 / 0 / 0

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

Сообщений: 116

1

18.10.2016, 15:47. Показов 22941. Ответов 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.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.

все поля модели и таблицы БД соответствуют друг другу (типы, их число и названия), делал повторно миграцию — всё чисто.
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

592 / 503 / 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



Понравилась статья? Поделить с друзьями:
  • An error occurred while saving entities to the database see inner exception for details перевод
  • An error occurred while running this request check postman console for more info
  • An error occurred while running the simulation and the simulation was terminated
  • An error occurred while running the manifest extension utility to sign the smtp data
  • An error occurred while running registry sysprep dlls halting sysprep execution dwret 0x3cf2