Db savechanges ошибка

I’m following this tutorial Creating Master-Details Windows Forms with the Entity Framework
but the db.Savechanges() isn’t working if I modified some column or add a new row. According to this video tutorial it will work but it doesn’t.

Product_Form.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RemoteSynchronizer
{
    public partial class Product : Form
    {

        ProductsEntities db = new ProductsEntities();
        public Product()
        {
            InitializeComponent();
        }

        private void Product_Form_Load(object sender, EventArgs e)
        {
            product_DBindingSource.DataSource = db.Product_D.ToList();
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {

        }

        private void product_DBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            // Product_D obj = new Product_D();
            // obj.PCode = pCodeTextBox.Text;
            // obj.Name = nameTextBox.Text;
            // obj.Batch = batchTextBox.Text;
            // obj.Expiry = expiryTextBox.Text;
            // obj.Price = priceTextBox.Text;

            //try
            // {
            //     Product_D temp = db.Product_D.Single(t => t.PCode == pCodeTextBox.Text);

            //     MessageBox.Show("Product Exists");
            // }
            // catch 
            // {
            //     db.Product_D.Add(obj);
                 db.SaveChanges();

             //}

        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {

        }

    }
}

When I try to use comment method in code it gives an error

Error

************** Exception Text **************
System.Data.Entity.Infrastructure.DbUpdateException: Unable to update the EntitySet 'Product_D' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation. ---> System.Data.UpdateException: Unable to update the EntitySet 'Product_D' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
   at System.Data.SqlClient.SqlGen.DmlSqlGenerator.ExpressionTranslator.Visit(DbScanExpression expression)
   at System.Data.Common.CommandTrees.DbScanExpression.Accept(DbExpressionVisitor visitor)
   at System.Data.SqlClient.SqlGen.DmlSqlGenerator.GenerateInsertSql(DbInsertCommandTree tree, SqlVersion sqlVersion, List`1& parameters)
   at System.Data.SqlClient.SqlGen.SqlGenerator.GenerateSql(DbCommandTree tree, SqlVersion sqlVersion, List`1& parameters, CommandType& commandType, HashSet`1& paramsToForceNonUnicode)
   at System.Data.SqlClient.SqlProviderServices.CreateCommand(DbProviderManifest providerManifest, DbCommandTree commandTree)
   at System.Data.SqlClient.SqlProviderServices.CreateCommand(DbCommandTree commandTree)
   at System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
   at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary`2 identifierValues)
   at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
   at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   --- End of inner exception stack trace ---
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at RemoteSynchronizer.Product.product_DBindingNavigatorSaveItem_Click(Object sender, EventArgs e) in e:StudyProjectRemoteSynchronizerRemoteSynchronizerProduct_Form.cs:line 50
   at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
   at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)
   at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
   at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
   at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
   at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
   at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.ToolStrip.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18010 built by: FX45RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
RemoteSynchronizer
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///E:/Study/Project/RemoteSynchronizer/RemoteSynchronizer/bin/Debug/RemoteSynchronizer.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.18016 built by: FX45RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Configuration
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Web
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Web/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Web.dll
----------------------------------------
System.Core
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
EntityFramework
    Assembly Version: 5.0.0.0
    Win32 Version: 5.0.20627.0
    CodeBase: file:///E:/Study/Project/RemoteSynchronizer/RemoteSynchronizer/bin/Debug/EntityFramework.DLL
----------------------------------------
System.Data.Entity
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Data.Entity/v4.0_4.0.0.0__b77a5c561934e089/System.Data.Entity.dll
----------------------------------------
Anonymously Hosted DynamicMethods Assembly
    Assembly Version: 0.0.0.0
    Win32 Version: 4.0.30319.18010 built by: FX45RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/mscorlib/v4.0_4.0.0.0__b77a5c561934e089/mscorlib.dll
----------------------------------------
Accessibility
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/Accessibility/v4.0_4.0.0.0__b03f5f7f11d50a3a/Accessibility.dll
----------------------------------------
System.Data
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Data/v4.0_4.0.0.0__b77a5c561934e089/System.Data.dll
----------------------------------------
System.Transactions
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Transactions/v4.0_4.0.0.0__b77a5c561934e089/System.Transactions.dll
----------------------------------------
System.Numerics
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Numerics/v4.0_4.0.0.0__b77a5c561934e089/System.Numerics.dll
----------------------------------------
System.Data.OracleClient
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Data.OracleClient/v4.0_4.0.0.0__b77a5c561934e089/System.Data.OracleClient.dll
----------------------------------------
System.Xml.Linq
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml.Linq/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.Linq.dll
----------------------------------------
System.EnterpriseServices
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.EnterpriseServices/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.EnterpriseServices.dll
----------------------------------------
EntityFrameworkDynamicProxies-RemoteSynchronizer
    Assembly Version: 1.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Data.Entity/v4.0_4.0.0.0__b77a5c561934e089/System.Data.Entity.dll
----------------------------------------
System.Runtime.Serialization
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929 built by: FX45RTMREL
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Runtime.Serialization/v4.0_4.0.0.0__b77a5c561934e089/System.Runtime.Serialization.dll
----------------------------------------
System.ComponentModel.DataAnnotations
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.17929
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.ComponentModel.DataAnnotations/v4.0_4.0.0.0__31bf3856ad364e35/System.ComponentModel.DataAnnotations.dll
----------------------------------------
Microsoft.SqlServer.Types
    Assembly Version: 11.0.0.0
    Win32 Version: 2011.0110.2100.060 ((SQL11_RTM).120210-1917 )
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.SqlServer.Types/11.0.0.0__89845dcd8080cc91/Microsoft.SqlServer.Types.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.

How to get rid of this problem? I’m trying to solve this by simple method db.savechanges() but it won’t work.

Before going through my answer, you must check, if you are attaching the item as shown in excepted answer or check this code:.

if (dbStudentDetails != null && dbStudentDetails.Id != 0)
{
   // update scenario
    item.Id = dbStudentDetails.Id;
    _context.Entry(dbStudentDetails).CurrentValues.SetValues(item);
    _context.Entry(dbStudentDetails).State = EntityState.Modified;
}
else
{
    // create scenario
    _context.StudentDetails.Add(item);
}

await _context.SaveChangesAsync();

If above solution doesn’t work, then check the below answer.

Saw a very wired issue, and thought to must answer this. as this can
be a major issue if you have lots of constraints and indexes in your
SQL.

db.SaveChanges() wasn’t throwing any error, but not working (I have tried Exception or SqlException). This was not working because the Unique constraint was not defined properly while creating the Entity Models.

How you can Identified the issue:

  • I connected my SQL Server and opened the SQL Profiler.
  • Just before the db.SaveChanges(), I cleared all my profiler logs and ran the db.SaveChanges(). It logged the statement. I copied the script from the profiler and ran the script in SQL Server.
  • And bingo, I can see the actual error, which is being thrown at SQL Server side.

(images: have some hints, how you can get the execute statement from Profiler and run on sql server)
enter image description here
enter image description here

What you can do For Entity Framework Core:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Students>().HasIndex(p => new { p.RollNumber, p.PhoneNumber }).IsUnique(true).IsClustered(false).HasDatabaseName("IX_Students_Numbers");
}

What you can do For Entity Framework 6 and below:


using System.Data.Entity.ModelConfiguration;

internal partial class StudentsConfiguration : EntityTypeConfiguration<Students>
{
    public StudentsConfiguration()
    {
        HasIndex(p => new { p.RollNumber, p.PhoneNumber }).IsUnique(true).IsClustered(false).HasName("IX_Students_Numbers");
    }
}

On 3/7/2011 8:05 PM, BruceMc wrote:

> Hello.

>

> No change. It still doesnt get past the SaveChanges call, yet doesnt

> throw an exception.

>

> I added print statements before and after the SaveChanges call, and the

> simple print after doesn’t get called, yet no exception is being thrown.

>

> Any clue would be appreciated.

>

> I guess my question is: how could this line pitch me out of the

> try/catch block without throwing an exception? Is there a mechanism that

> I am missing here?

>

> Thanks.

>

Below is how I like to deal with opening and closing a connection. I

think the link below applies to more than using steament and a calling a

service.

using System.Linq;

using DataAccessLayer.IDAL;

using DataAccessLayer.Model;

using DataAccessLayer.DTO;

using System.Data.EntityClient;

using System.Collections.Generic;

 namespace DataAccessLayer

{

    public class Article :IArticle

    {

        private const string pcdb = «name=PublishingCompanyEntities»;

         public DTOArticle GetArticle(int id)

        {

            var dto = new DTOArticle();

             using (var conn = new EntityConnection(pcdb))

            using (var db = new PublishingCompanyEntities(conn))

            {

                try

                {

                    var article = (from a in db.Articles.Where(a =>

                         a.ArticleID == id)select a).First();

                     dto.ArticleID = article.ArticleID;

                    dto.AuthorID = (int) article.AuthorID;

                    dto.Body = article.Body;

                    dto.Tille = article.Title;

                 }

                finally

                {

                    conn.Close();

                }

            }

             return dto;

        }

         public List<DTOArticle> GetArticles()

        {

            var dtos = new List<DTOArticle>();

             using (var conn = new EntityConnection(pcdb))

            using (var db = new PublishingCompanyEntities(conn))

            {

                try

                {

                    var articles = (from a in db.Articles select

a).ToList();

                     dtos.AddRange(articles.Select(article => new DTOArticle

                    {

                        ArticleID = article.ArticleID,

                        AuthorID = (int) article.AuthorID,

                        Body = article.Body,

                        Tille = article.Title

                    }));

                }

                finally

                {

                    conn.Close();

                }

            }

             return dtos;

        }

         public void UpdateArticles(List<DTOArticle> articles)

        {

            using (var conn = new EntityConnection(pcdb))

            using (var db = new PublishingCompanyEntities(conn))

            {

                try

                {

                    foreach (var article in articles)

                    {

                        var artc = new Model.Article { ArticleID =

article.ArticleID };

                         db.AttachTo(«Articles», artc);

                        artc.AuthorID = article.AuthorID;

                        artc.Title = article.Tille;

                        artc.Body = article.Body;

                        db.SaveChanges();

                    }

                }

                finally

                {

                    conn.Close();

                }

            }

        }

         public void AddArticles(List<DTOArticle> articles)

        {

            using (var conn = new EntityConnection(pcdb))

            using (var db = new PublishingCompanyEntities(conn))

            {

                try

                {

                    foreach (var article in articles)

                    {

                        var artc = new Model.Article

                                       {

                                           AuthorID = article.AuthorID,

                                           Title = article.Tille,

                                           Body = article.Body

                                       };

                         db.AddToArticles(artc);

                        db.SaveChanges();

                    }

                }

                finally

                {

                    conn.Close();

                }

            }

        }

         public void DeleteArticle(DTOArticle article)

        {

            var art = new Model.Article { ArticleID = article.ArticleID };

             using (var conn = new EntityConnection(pcdb))

            using (var db = new PublishingCompanyEntities(conn))

            {

                try

                {

                    db.AttachTo(«Articles», art);

                    db.DeleteObject(art);

                    db.SaveChanges();

                }

                finally

                {

                    conn.Close();

                }

            }

        }

    }

}

Passing data from one controller

Beginners often ask this question — «What course of action should I take when a
call to SaveChanges() fails?» The answer may vary based on a given situation and
requirement. However, in many cases the following course of actions can be
performed:

  • Trap the exception caused by the failed call to SaveChanges().
  • Find out all the errors that occurred during the SaveChanges() call.
  • Find out which entities caused the errors.
  • Either display the errors and entities causing errors to the user or log
    that information somewhere.
  • Based on whether an entity was added, modified or deleted rollback its
    effect.

Let’s see how the above steps can be performed by developing a simple console
application.

Begin by creating a new project of type Console Application. Then add Models
folder to it and generate ADO.NET Entity Data Model for the Customers and
Employees tables of the Northwind database. The following figure shows the
Customer and Employee entities:

Now add the following code in the Main() method:

static void Main(string[] args)
{
    NorthwindEntities db = new NorthwindEntities();

    Customer obj1 = new Customer();
    obj1.CustomerID = "This is a long CustomerID";
    obj1.CompanyName = "Abcd";
    obj1.ContactName = "Abcd";
    obj1.Country = "USA";
    db.Customers.Add(obj1);

    Employee obj2 = db.Employees.Find(1);
    obj2.FirstName = "This is a long first name value";

    db.SaveChanges();
}

The above code attempts to add a new Customer to the Customers table and also
attempts to modify an existing Employee with EmployeeID of 1. Notice that the
code deliberately sets CustomerID property of the Customer object and FirstName
property of the Employee object to some long value — something that won’t fit in
the column length.

When you can SaveChanges() obviously it is going to throw an exception. The
following figure shows the exception thrown by an unsuccessful call to
SaveChanges().

As shown above an unsuccessful call to SaveChanges() threw
DbEntityValidationException exception. This exception class can be used to
obtain more information about all the errors that occurred during the
SaveChanges() call.

Now modify the Main() as shown below:

try
{
    db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
    foreach (DbEntityValidationResult item in ex.EntityValidationErrors)
    {
        // Get entry

        DbEntityEntry entry = item.Entry;
        string entityTypeName = entry.Entity.GetType().Name;

        // Display or log error messages

        foreach (DbValidationError subItem in item.ValidationErrors)
        {
            string message = string.Format("Error '{0}' occurred in {1} at {2}", 
                     subItem.ErrorMessage, entityTypeName, subItem.PropertyName);
            Console.WriteLine(message);
        }
    }
}

Now the call to SaveChanges() is wrapped inside a try…catch block. The
catch block traps DbEntityValidationException exception. The
EntityValidationErrors collection of DbEntityValidationException class contains
a list of validation errors. Each item of EntityValidationErrors collection is
of type DbEntityValidationResult. Instead of showing a generic message the above
code forms a descriptive error messages. This is done by finding which all
entities caused errors. In each iteration of the outer foreach loop, the entry
causing the error is accessed using the Entry property of
DbEntityValidationResult class. The Entry property is of type DbEntityEntry. The
Entity property of this DbEntityEntry gives you the entity that caused the
error. The above code simply obtains a fully qualified name of the entity type
(for example, ProjectName.Models.Customer and ProjectName.Models.Employee).

The inner foreach loop iterates through the ValidationErrors collection of
DbEntityValidationResult under consideration. Each item of ValidationErrors
collection is of type DbValidationError. The PropertyName and ErrorMessage
properties of DbValidationError class give you the entity property that caused
the error (such as CustomerID and FirstName) and the actual error message. These
properties along with the entity type name are used to form a descriptive error
message. In this example the error message is displayed on the console but you
can log it in some text file if you so wish. The following figure shows how the
error messages are displayed on the console.

So far we displayed the descriptive error messages to the end user. Now it’s
time to rollback the changes so that the entities causing error are either
isolated from the model or the changes are discarded (in case of modified
entities). Modify the code in the catch block as shown below:

...
...
foreach (DbValidationError subItem in item.ValidationErrors)
{
    string message = string.Format("Error '{0}' occurred in {1} at {2}", 
             subItem.ErrorMessage, entityTypeName, subItem.PropertyName);
    Console.WriteLine(message + "nn");
}

// Rollback changes

switch (entry.State)
{
    case EntityState.Added:
        entry.State = EntityState.Detached;
        break;
    case EntityState.Modified:
        entry.CurrentValues.SetValues(entry.OriginalValues);
        entry.State = EntityState.Unchanged;
        break;
    case EntityState.Deleted:
        entry.State = EntityState.Unchanged;
        break;
}

The above code checks the State property of the DbEntityEntry causing the
error. The State property is of enumeration type — EntityState. If the current
State is Added, it is changed to Detached so that the entry won’t be considered
a part of the DbSet for future calls. If the current State is Modified, the
modified values (the values causing the error) are flushed out by replacing them
with the OriginalValues. Notice how the original values are obtained using
SetValues() method and OriginalValues property. If the State is Deleted, it is
changed to Unchanged so that the entity is undeleted.

Once you display the errors and rollback any changes to the entities causing
the errors, you may give another chance to the user to make the changes and then
call SaveChanges() again.

That’s it for now! Keep coding !!

Usaga,

Код

System.Data.Entity.Infrastructure.DbUpdateException не обработано
  HResult=-2146233087
  Message=При обновлении записей произошла ошибка. Подробные сведения см. во внутреннем исключении.
  Source=EntityFramework
  StackTrace:
       в System.Data.Entity.Internal.InternalContext.SaveChanges()
       в System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
       в System.Data.Entity.DbContext.SaveChanges()
       в Procat.MainWindow.Save_Click(Object sender, RoutedEventArgs e) в D:ProcatProcatMainWindow.xaml.cs:строка 71
       в System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       в System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       в System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
       в System.Windows.Controls.Primitives.ButtonBase.OnClick()
       в System.Windows.Controls.Button.OnClick()
       в System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       в System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
       в System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       в System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       в System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       в System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
       в System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
       в System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       в System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       в System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       в System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       в System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       в System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
       в System.Windows.Input.InputManager.ProcessStagingArea()
       в System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
       в System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
       в System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
       в System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       в System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       в MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       в MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       в System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       в System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
       в System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       в MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       в MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       в System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       в System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       в System.Windows.Application.RunDispatcher(Object ignore)
       в System.Windows.Application.RunInternal(Window window)
       в System.Windows.Application.Run(Window window)
       в System.Windows.Application.Run()
       в Procat.App.Main() в D:ProcatProcatobjDebugApp.g.cs:строка 0
       в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       в System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       HResult=-2146233087
       Message=При обновлении записей произошла ошибка. Подробные сведения см. во внутреннем исключении.
       Source=System.Data.Entity
       StackTrace:
            в System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
            в System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
            в System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
            в System.Data.Entity.Internal.InternalContext.SaveChanges()
       InnerException: 
            Class=14
            ErrorCode=-2146232060
            HResult=-2146232060
            LineNumber=1
            Message=Violation of PRIMARY KEY constraint 'PK__tmp_ms_x__3214EC0704A01891'. Cannot insert duplicate key in object 'dbo.Procatoff'. The duplicate key value is (0).
The statement has been terminated.
            Number=2627
            Procedure=""
            Server=(LocalDB)MSSQLLocalDB
            Source=.Net SqlClient Data Provider
            State=1
            StackTrace:
                 в System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                 в System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
                 в System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
                 в System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
                 в System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
                 в System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
                 в System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
                 в System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
                 в System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
                 в System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
                 в System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
            InnerException:



0



Понравилась статья? Поделить с друзьями:
  • Dayz пустая ошибка
  • Dayz ошибка при запуске лаунчера
  • Dayz ошибка мода cf
  • Dayz ошибка steam cloud
  • Dayz ошибка smartsteamloader