New Posts New Posts RSS Feed: Error saving list of related objects
  FAQ FAQ  Forum Search   Calendar   Register Register  Login Login

Error saving list of related objects

 Post Reply Post Reply
Author
hueha View Drop Down
Newbie
Newbie


Joined: 23-Jul-2010
Posts: 38
Post Options Post Options   Quote hueha Quote  Post ReplyReply Direct Link To This Post Topic: Error saving list of related objects
    Posted: 18-Sep-2010 at 8:43am
I get the following error when trying to save (using devforce 6.0.5)

Entity Save Error: System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_CompanyLocation_Company". The conflict occurred in database "jts2", table "dbo.CompanyLocation", column 'CompanyID'. The statement has been terminated. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) 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) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() 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) --- End of inner exception stack trace --- 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 IdeaBlade.EntityModel.Edm.EdmSaveExecutor.ProcessSaves(IEnumerable`1 groupsByType) at IdeaBlade.EntityModel.Edm.EdmSaveExecutor.SaveWithinContext() at IdeaBlade.EntityModel.Edm.EdmSaveExecutor.Save(DataSourceResolver dataSourceResolver, IDataSourceKey dsKey, SaveWorkState workState)

What I'm doing is trying to delete a company using an entitygraph

 public List<EntitySpan> GetSpan()
        {
             List<EntitySpan> spans = new List<EntitySpan>();

            EntitySpan aSpan = new EntitySpan(typeof(Company), EntityRelations.FK_CompanyLocation_Company);
            spans.Add(aSpan);
            aSpan = new EntitySpan(typeof(Company), EntityRelations.FK_CompanyContact_Company);
            spans.Add(aSpan);
            return spans;
        }

        public void GetEntityGraphAsync(Action<IList<Object>> callback)
        {    
           //First ensure all children are loaded
            IEntityQuery<Company> query =((JTS2Entities) this.EntityAspect.EntityManager).Companies.Where(c => c.CompanyID == this.CompanyID)
            .Include(EntityPropertyNames.CompanyContacts)
            .Include(EntityPropertyNames.CompanyLocations);

            ((JTS2Entities)this.EntityAspect.EntityManager).ExecuteQueryAsync<Company>(query
                , (o) => {
                    // Create roots list and add the employee.
                    List<Entity> roots = new List<Entity>();

                    roots.Add(this);

                    // Add span(s).

                    List<EntitySpan> spans = GetSpan();

                    // Get entity graph for entities in roots

                    EntityState entityState = EntityState.AllButDetached;

                    IList<Object> entityGraph = this.EntityAspect.EntityManager.FindEntityGraph(roots, spans, entityState);
                    callback(entityGraph);
                }
                , null);
        }

after getting the entityGraph i iterate over it and delete them

           foreach (var item in entityGraph)
                   {
                       ((Entity)item).EntityAspect.Delete();
                   }

then I call save
_mgr.SaveChangesAsync(entityGraph, null, SaveCallBack, null);

What I think is happening is that it is deleting them in the wrong order.  It's trying to delete the company first before the location.  Possibly by deleting the location I have confused the framework that there are no relations?

Also, this only happens if I just created the company and location.  If the company (and its locations and contacts) was just loaded from the database the delete seems to work.


Back to Top
sbelini View Drop Down
IdeaBlade
IdeaBlade
Avatar

Joined: 13-Aug-2010
Location: Oakland
Posts: 786
Post Options Post Options   Quote sbelini Quote  Post ReplyReply Direct Link To This Post Posted: 07-Oct-2010 at 12:11pm
hueha,
 
The error "The DELETE statement conflicted with the REFERENCE constraint..." comes from the SQL server, so you are most likely violating a reference constraint.
 
As for it only happening with elements that have just been created, I could not reproduce it here.
 
When you mention just created, do you mean not saved into the datasource yet? (i.e. existing only in the cache)
If the just created entities were actually saved into the datasource, does the issue persists on subsequent executions? (i.e. on the subsequent executions these entities would be "loaded from the db" and not "just created" anymore)
 
Can you upload a simple test case reproducing the issue above stated, so I can further investigate the issue?
Back to Top
hueha View Drop Down
Newbie
Newbie


Joined: 23-Jul-2010
Posts: 38
Post Options Post Options   Quote hueha Quote  Post ReplyReply Direct Link To This Post Posted: 07-Oct-2010 at 3:31pm
As in I created and saved the objects to the database in this session.  If I quit my application after saving and then try to delete it seems to work.    I will try and make a sample app but it may take a few days
Back to Top
hueha View Drop Down
Newbie
Newbie


Joined: 23-Jul-2010
Posts: 38
Post Options Post Options   Quote hueha Quote  Post ReplyReply Direct Link To This Post Posted: 10-Oct-2010 at 3:37am
I figured out the problem.  I was using the entityaspect delete on the contact (one side of the many to many) and removing it from the contact list in the locaton (the other side of the many to many).  When I removed the location from the locations list in contact before deleting it then it worked
Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down