Insert throws exception, but actual db insert succeeds

Posts   
 
    
Posts: 13
Joined: 27-Aug-2007
# Posted on: 19-Oct-2007 05:30:46   

I have a RadGrid which is databound to a table called SearchTreeConstraint. In the database (SQL Server) I have a relationship between SearchTreeConstraint and the parent, SearchTree, and thus an fkSearchTreeID.

When I add a new constraint via the datagrid, I have stepped through and verified that the fkSearchTreeId is getting set correctly. Then I call "entity.save()" and it appears to succeed without a hitch. I check the database and the item is correctly saved to the database. But right after this insert happens, LLBLGen throws the following exception in the CmssearchTreeConstraintDAO class on the "AddNew" method:

{"An exception was caught during the execution of an action query: Cannot insert the value NULL into column 'fkSearchTreeID', table 'ValleyTractorCMSDB.dbo.CMSSearchTreeConstraint'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated.. Check InnerException, QueryExecuted and Parameters of this exception to examine the cause of this exception."}

If I examine the objects in the debugger, sure enough fkSearchTreeID is null, but in the database it's already saved and fine. I'm lost.

I've tried manually saving the record to the database (not using entity.save(), but actually generating sql and saving) and the problem persists... so I don't really think it has to do with the entity saving, but possibly the binding after the insert is completed?

This component was supposed to be done yesterday and I can't get this problem to go away, nor can I seem to catch it anywhere.

Your help or thoughts would be wonderful. Thanks for your time.

-Renée Firefly, Wenatchee

Here is the complete error:

Server Error in '/Website' Application.
--------------------------------------------------------------------------------

Cannot insert the value NULL into column 'fkSearchTreeID', table 'ValleyTractorCMSDB.dbo.CMSSearchTreeConstraint'; column does not allow nulls. INSERT fails.
The statement has been terminated. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'fkSearchTreeID', table 'ValleyTractorCMSDB.dbo.CMSSearchTreeConstraint'; column does not allow nulls. INSERT fails.
The statement has been terminated.

Source Error: 


Line 606:       {
Line 607:           CmssearchTreeConstraintDAO dao = (CmssearchTreeConstraintDAO)CreateDAOInstance();
Line 608:           return dao.AddNew(base.Fields, base.Transaction);
Line 609:       }
Line 610:       


Source File: C:\FIREFLY\Projects\ValleyTractor\ValleyTractor.DAL\EntityClasses\CmssearchTreeConstraintEntity.cs Line: 608 

Stack Trace: 


[SqlException (0x80131904): Cannot insert the value NULL into column 'fkSearchTreeID', table 'ValleyTractorCMSDB.dbo.CMSSearchTreeConstraint'; column does not allow nulls. INSERT fails.
The statement has been terminated.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +862234
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +739110
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1956
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +149
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +903
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132
   System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +415
   System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135
   SD.LLBLGen.Pro.ORMSupportClasses.ActionQuery.Execute() +551

[ORMQueryExecutionException: An exception was caught during the execution of an action query: Cannot insert the value NULL into column 'fkSearchTreeID', table 'ValleyTractorCMSDB.dbo.CMSSearchTreeConstraint'; column does not allow nulls. INSERT fails.
The statement has been terminated.. Check InnerException, QueryExecuted and Parameters of this exception to examine the cause of this exception.]
   SD.LLBLGen.Pro.ORMSupportClasses.ActionQuery.Execute() +848
   SD.LLBLGen.Pro.ORMSupportClasses.BatchActionQuery.Execute() +122
   SD.LLBLGen.Pro.ORMSupportClasses.DaoBase.ExecuteActionQuery(IActionQuery queryToExecute, ITransaction containingTransaction) +128
   SD.LLBLGen.Pro.ORMSupportClasses.DaoBase.AddNew(IEntityFields fields, ITransaction containingTransaction) +331
   ValleyTractor.DAL.EntityClasses.CmssearchTreeConstraintEntity.InsertEntity() in C:\FIREFLY\Projects\ValleyTractor\ValleyTractor.DAL\EntityClasses\CmssearchTreeConstraintEntity.cs:608
   SD.LLBLGen.Pro.ORMSupportClasses.EntityBase.CallInsertEntity() +27
   SD.LLBLGen.Pro.ORMSupportClasses.DaoBase.PersistQueue(List`1 queueToPersist, Boolean insertActions, ITransaction transactionToUse, Int32& totalAmountSaved) +833
   SD.LLBLGen.Pro.ORMSupportClasses.EntityBase.Save(IPredicate updateRestriction, Boolean recurse) +983
   SD.LLBLGen.Pro.ORMSupportClasses.EntityBase.Save(Boolean recurse) +139
   SD.LLBLGen.Pro.ORMSupportClasses.LLBLGenProDataSourceView.ExecuteInsert(IDictionary values) +352
   System.Web.UI.DataSourceView.Insert(IDictionary values, DataSourceViewOperationCallback callback) +72
   Telerik.WebControls.GridTableView.PerformInsert(GridEditableItem editedItem, Boolean suppressRebind) +237
   Telerik.WebControls.GridTableView.PerformInsert(GridEditableItem editedItem) +33
   Telerik.WebControls.GridTableView.PerformInsert() +48
   Telerik.WebControls.GridCommandEventArgs.ExecuteCommand(Object source) +4775
   Telerik.WebControls.RadGrid.OnBubbleEvent(Object source, EventArgs e) +171
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35
   Telerik.WebControls.GridItem.OnBubbleEvent(Object source, EventArgs e) +57
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35
   Telerik.WebControls.GridItem.OnBubbleEvent(Object source, EventArgs e) +147
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35
   System.Web.UI.WebControls.ImageButton.OnCommand(CommandEventArgs e) +115
   System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +171
   System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102
Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 19-Oct-2007 11:55:29   

I'd say that there are 2 Inserts being issued, one succeeds and the other fails.

I have a RadGrid which is databound to a table called SearchTreeConstraint.

How databinding is done? Is this a windows or a web applications?

Then I call "entity.save()"

Would you please post a complete code sniappet?

Posts: 13
Joined: 27-Aug-2007
# Posted on: 19-Oct-2007 19:42:14   

I have attached the relavant code (which is basically most of the two files (aspx and aspx.cs)).

The databinding is done by LLBLGenDataSources in the aspx. Thanks for your time.

Hope this helps, Renée

Attachments
Filename File size Added on Approval
RelavantCode.zip 3,973 19-Oct-2007 19:42.25 Approved
daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 20-Oct-2007 07:51:31   

Hi Renée,

I can see the _LLBLGenProDataSource _here

<llblgenpro:llblgenprodatasource id="LLBLGenProDataSourceConstraints" runat="server"  datacontainertype="EntityCollection"
    entitycollectiontypename="ValleyTractor.DAL.CollectionClasses.CmssearchTreeConstraintCollection, ValleyTractor.DAL" >
</llblgenpro:llblgenprodatasource>

As isn't set LivePersistence, the default is true, that means _LLLBLGenProDataSource _perform the save by itself.

However at method **HandleConstraintChanges **you explicitly call entity.Save(); that means that two INSERTS are performed. One call is needless. I guess you want to perform the save manually, so you have to LivePersistence = false and implement a PerformWork. For more info read LLBLGenPro Help - Using generated code - SelfServicing - Databinding at designtime and runtime - Databinding with ASP.NET 2.0

Hope this can be useful wink

David Elizondo | LLBLGen Support Team
Posts: 13
Joined: 27-Aug-2007
# Posted on: 22-Oct-2007 20:17:46   

daelmo wrote:

Hi Renée,

I can see the _LLBLGenProDataSource _here

<llblgenpro:llblgenprodatasource id="LLBLGenProDataSourceConstraints" runat="server"  datacontainertype="EntityCollection"
    entitycollectiontypename="ValleyTractor.DAL.CollectionClasses.CmssearchTreeConstraintCollection, ValleyTractor.DAL" >
</llblgenpro:llblgenprodatasource>

As isn't set LivePersistence, the default is true, that means _LLLBLGenProDataSource _perform the save by itself.

However at method **HandleConstraintChanges **you explicitly call entity.Save(); that means that two INSERTS are performed. One call is needless. I guess you want to perform the save manually, so you have to LivePersistence = false and implement a PerformWork. For more info read LLBLGenPro Help - Using generated code - SelfServicing - Databinding at designtime and runtime - Databinding with ASP.NET 2.0

Hope this can be useful wink

This is really helpful information, and I think I understand now at least why it was happening. I have two questions:

When I turn "LivePersistance" to false, current grid items stop showing up - any ideas why?

If I implement a "PerformWork" method, how can I access the entity that is about to be saved and change the fkSearchTreeID to what's came on the query string? I've spent time looking in the documentation, but I can't find any examples. I've browsed the e.Uow item but don't even see the fkSearchTreeID value. I went back to using my HandleConstraintChanges because it works, but only if LivePersistence is off, but then I can't see my current grid items.

Thanks for your help so far, it's been great. I feel like I'm almost there.

Thanks, Renée

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 23-Oct-2007 07:29:54   

Hi Renée,

When you use LivePersistance=false, you have to handle this events:

PerformSelect PerformWork PerformDBCount

Here is an example of those methods:

protected void customerDS_PerformSelect(object sender, PerformSelectEventArgs2 e)
    {
        // fetch all customers using the information passed in via the 
        // PerformSelectEventArgs2 object. This select doesn't have to perform any paging, as the
        // data is for a combo box.
        using(DataAccessAdapter adapter = new DataAccessAdapter())
        {
            adapter.FetchEntityCollection(e.ContainedCollection, e.Filter, 
                    e.MaxNumberOfItemsToReturn, e.Sorter, e.PrefetchPath);
        }
    }

    protected void orderDS_PerformGetDbCount(object sender, PerformGetDbCountEventArgs2 e)
    {
        // get the total number of orders which match the filter passed in via the
        // PerformGetDbCountEventArgs2.
        using(DataAccessAdapter adapter = new DataAccessAdapter())
        {
            e.DbCount = adapter.GetDbCount(e.ContainedCollection, e.Filter);
        }
    }

    protected void orderDS_PerformSelect(object sender, PerformSelectEventArgs2 e)
    {
        // fetch all orders which are in the selected page using the filter passed in
        // via the PerformSelectEventArgs2 object. 
        using(DataAccessAdapter adapter = new DataAccessAdapter())
        {
            adapter.FetchEntityCollection(e.ContainedCollection, e.Filter,
                    e.MaxNumberOfItemsToReturn, e.Sorter, e.PrefetchPath, 
                    e.PageNumber, e.PageSize);
        }
    }

firefly-renee wrote:

I've browsed the e.Uow item but don't even see the fkSearchTreeID value. I went back to using my HandleConstraintChanges because it works, but only if LivePersistence is off, but then I can't see my current grid items.

You could use these UOW methods:

You can also check LLBLGenPro Reference Manual to get more info wink

David Elizondo | LLBLGen Support Team