Avatar of LisaTatum
LisaTatum

asked on 

LINQ to Entities: UpdateException - after it occurs whole database seems to be screwed

Hello,

this is my first question here. If I could I would give this question 1000 points, because an answer is  very important to me. I already asked on microsoft forum, but nobody did answer... If someone has a helping answer in finding a solution I decide to suscribe EE - not kidding -

My problem is a easy test scenario:

I have just ONE single Entity called DEPARTMENT.
It has ONE field called department_name which is set as primary key in the database.

When I add a department name to the database which already exists I get an UpdateException.

Error:

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(Boolean acceptChangesDuringSave) at System.Data.Objects.ObjectContext.SaveChanges()
at Company.DepartmentPresenter.View_AddDepartment(String departmentName) in C:\MVP.EF\DepartmentPresenter.cs:line 43.
A first chance exception of type 'System.Data.UpdateException' occurred in System.Data.Entity.dll

After I got that UpdateException I tried to add other departments names not yet saved in the database. But whatever name I add now I get always an UpdateException independendly what department name I  have added to the database.
Or I delete department names from the ListBox and they get deleted in the ListBox but not in the database and everytime I try to delete a department an UpdateException is thrown.


Why does Entity Framework tell me about a Primary Key violation AGAIN although I enter a value not saved yet in the database ?

There must be something breaking my database behaviour...


VIEW:
 
public partial class MainWindowView : Form , IDepartmentView
    {       
        private IDepartmentPresenter departmentPresenter;            
        public event AddViewDepartmentDataHandler AddViewDepartmentData;
        public event DeleteViewDepartmentDataHandler DeleteViewDepartmentData;
        public event DisposeContextHandler DisposeContext;
 
        public MainWindowView()
        {
            InitializeComponent();
            departmentPresenter = new DepartmentPresenter(this);
            
        }
 
        public void DataToBindingSource(Object queryDepartment)
        {
            dEPARTMENTBindingSource.DataSource = queryDepartment;             
        }  
 
        private void addDepartmentButton_Click_1(object sender, EventArgs e)
        {
            if (AddViewDepartmentData != null)
                AddViewDepartmentData(departmentTextBox.Text);            
        }
 
        private void deleteDepartmentButton_Click(object sender, EventArgs e)
        {
            if (DeleteViewDepartmentData != null)
            {
                DEPARTMENT department = (DEPARTMENT)departmentListBox.SelectedItem;
 
                if (department == null)
                {
                    MessageBox.Show("Sie müssen ein existierendes Department wählen", "Fehler");
                    return;
                }                 
 
                DeleteViewDepartmentData(department);
            }                
        }                        
    }
 
PRESENTER:
 
 class DepartmentPresenter : IDepartmentPresenter
    {
        private companyEntities mycontext = new companyEntities();
        private IDepartmentView view;
        private ObjectQuery<DEPARTMENT> queryDepartment;           
 
        public DepartmentPresenter(IDepartmentView view)
       {           
           this.view = view;       
           LoadDepartments();
           view.AddViewDepartmentData    += View_AddDepartment;  
           view.DeleteViewDepartmentData += View_DeleteDepartment;           
       }
 
        private void LoadDepartments()
        {
            try
            {
                queryDepartment = mycontext.DEPARTMENT;
                this.view.DataToBindingSource(queryDepartment);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.StackTrace);
            }
        }
 
        private void View_AddDepartment(String departmentName)
        {
            var department = new DEPARTMENT();
 
            try
            {
                department.department_name = departmentName;
                mycontext.AddToDEPARTMENT(department);
                mycontext.SaveChanges();
                
                this.view.DataToBindingSource(queryDepartment.Execute(MergeOption.AppendOnly));                
            }
            catch (UpdateException ex)
            {
                Console.WriteLine("Error: " + ex.StackTrace);
                MessageBox.Show("The department: " + departmentName + " already exists", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }            
        }
 
        private void View_DeleteDepartment(DEPARTMENT department)
        {
            try
            {
                mycontext.DeleteObject(department);
                mycontext.SaveChanges();
            }
            catch (UpdateException ex)
            {
                Console.WriteLine("Error: " + ex.StackTrace);              
            }
        }
    }

Open in new window

.NET ProgrammingDatabases

Avatar of undefined
Last Comment
Fernando Soto
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of LisaTatum
LisaTatum

ASKER

I give you all my points :) Thank you very verry very very much!


 I tried your code snippet on my SQLite database and it worked fine!

I tried your code snippet on my SQL Compact Edition 3.5 database and it did not work ?

Any explanation for that before I give an A rating?


Avatar of LisaTatum
LisaTatum

ASKER

As I can not edit my comment I make a new one because I forgot 3 things:

1. Using SQL CE database the exception is called EntityException not UpdateException...

You have any explanation for that?

At the moment I can not even add any department name to my Entity using a surrogate key thats ridiculous and happens only with the SQL CE database. OK I do not really care as I use SQLite for my programm...

2. There are 2 ebooks out for Entity Framework learning:

   - Commercial ebook by Julia Lerman: Programming Entity Framework as Rough Cut version: http://learnentityframework.com/

   - Free PDF 500 Pages about Entity Framework by zeeshanhirani

http://cid-245ed00edb4c374e.skydrive.live.com/browse.aspx/Public

3. To my 130 points did you still recieve any bonus points ?

I can really recommend the latter PDF because it has many many test scenarios and code examples :)




Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi LisaTatum;

To your question, "I tried your code snippet on my SQL Compact Edition 3.5 database and it did not work ?", Is the SQL Compact Edition 3.5 throwing the same error? Is it going into the catch statement block?

Fernando
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi LisaTatum;

To your question, "Using SQL CE database the exception is called EntityException not UpdateException...You have any explanation for that?", Sorry I do not know why Microsoft did it that way but this answer my last question in the last post and is most likely the reason why it is not working in the SQL Compact Edition.

To your question, "To my 130 points did you still receive any bonus points ?", This will happen when the question is closed.

Thank you very much for the links I will read them.

Fernando
Avatar of LisaTatum
LisaTatum

ASKER

not same error message as already stated before:

A first chance exception of type 'System.Data.EntityException' occurred in System.Data.Entity.dll

no its not going into the catch block its not even saving ANY data, very weird... ??

[URL=http://imageshack.us][IMG]http://img227.imageshack.us/img227/6802/testly6.gif[/IMG][/URL]
Avatar of LisaTatum
LisaTatum

ASKER

ups there is a file attach button...

test.gif
Avatar of LisaTatum
LisaTatum

ASKER

Thank you very much again. I will stick to SQLite good free stuff and 25 % faster than SQL CE ;-)
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi LisaTatum;

The reason why it is not working in the SQL CE is because it is throwing a different exception and therefore not deleting the object from the entity class. try the code snippet below to catch either exception.

Fernando
catch (UpdateException ex)
{
    Console.WriteLine("Error: " + ex.StackTrace);
    MessageBox.Show("The department: " + departmentName + " already exists", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    mycontext.DeleteObject(department);
    mycontext.SaveChanges();
}
catch (EntityException ex)
{
    Console.WriteLine("Error: " + ex.StackTrace);
    MessageBox.Show("The department: " + departmentName + " already exists", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    mycontext.DeleteObject(department);
    mycontext.SaveChanges();
}

Open in new window

Avatar of LisaTatum
LisaTatum

ASKER

the catch for the SQL CE did not work :/
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Did it enter the catch at all?
Avatar of LisaTatum
LisaTatum

ASKER

as you can see from my attached window it stopped at the SaveChanges() method.
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Try placing a catch all exception block as the last catch block in the try/catch structure. Then read the stack trace and see what type of exception was thrown then create a catch block for that type of exception.

// The catch all Block
catch
{
    Console.WriteLine("Error: " + ex.StackTrace);
    MessageBox.Show("The department: " + departmentName + " already exists", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    mycontext.DeleteObject(department);
    mycontext.SaveChanges();
}
.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo