entity framework - how do i know which property threw exception during save? - entity-framework-4

I have a bunch of entities with hundreds of fields in SQL, dozens are non nullable. I was hoping to create the entity, save and see which field its complaining about so that I can easily include this (very quick/easy to do using unit test), but the info i get back from EF does not display which field/property caused the error? Why would this be? I even did try/catch, output exception and no additional info about the problem :-(
System.Data.UpdateException : An error occurred while updating the entries. See the inner exception for details.
----> System.Data.SqlTypes.SqlTypeException : SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
at PaymentDomain.IntegrationTests.EFTestSetup.Test() in EFTestSetup.cs: line 40
--SqlTypeException
at System.Data.SqlClient.TdsParser.TdsExecuteRPC(_SqlRPC[] rpcArray, Int32 timeout, Boolean inSchema, SqlNotificationRequest notificationRequest, TdsParserStateObject stateObj, Boolean isCommandProc, Boolean sync, TaskCompletionSource`1 completion, Int32 startRpc, Int32 startParam)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, ref Task task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, ref Task task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
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)
Cool, how bout something like: CreateDate
Thanks...

You can use DbContext.GetValidationErrors() method to retrieve validation rules break information. Article on MSDN.

Related

nullable LocalDate causes validation error if empty fields are submitted

If I create a Domain Object with a nullable LocalDate, the scaffolding editor throws a validation error if the date is empty: Cant populate a class org.joda.time.LocalDate without a year
This seems to come from within the Joda DateTimeStructuredBindingEditor.getPropertyValue
Does anyone know how to prevent this validation problem?
I'm not positive, but if the issue is coming from the scaffolding, it's possible that it is sending a blank date, not a null one.
I would try to:
1 - Check if the localDate is actually null before you save it.
2 - Add "blank: true" as a constraint. You shouldn't need this, as it's not a string, but it may work.
http://grails.org/doc/latest/ref/Constraints/nullable.html

breeze: unexpected error in getEntityGraph

I use getEntityGraph extension and it works fine except in the following scenario:
add a new entity
don't save it and call setDeleted on the entity
call getEntityGraph by passing the entity and a np collection as parameters
When makePathSegmentFn is called, it crashes on this line :
grps.forEach(function(grp) {
vals = vals.concat(grp._entities.filter(function (en) {
return en.getProperty(fkName) === keyValue;
}));
});
en is null so it raises an exception. I've worked around the problem by checking if en is null and every seems to work fine. But perhaps that should be done in the original code if it's a bug ? Note that only one entity is null amongst all the entities in the np collection. I guess that's the one that was deleted, but can't tell for sure.
Update 29 April 2014
OK ... I get it now. You're talking about a deleted child entity, not a detached root entity.
Thanks for identifying this bug. I added a test for this scenario to DocCode, then fixed the bug. Both changes pushed to github. They will appear in the next official release. You can get the current getEntityGraph.js from github right now.
Original answer
I can't duplicate the particular failure you describe ... because getEntityGraph throws long before it gets to the makePathSegmentFn ... as it should do!
getEntityGraph is supposed to throw an exception (e.g., "'getEntityGraph' root[0] is a detached entity") when any of the root entities passed in are 'Detached'.
When you create a new entity and immediately delete it (without saving it first), its state changes from 'Added' to 'Detached'; it is no longer an entity in cache. That is expected behavior (see "EntityState transitions" in the "Inside the Entity" documentation topic). That's what happens when I follow your repro steps exactly.
Please provide a jsFiddle or plunker that demonstrates the error.

VB .NET MVC LinqToSql exception with Update/Insert methods

First time posting. I have been going round and around with this one and no one seems to have the same problem I do.
When I try to either update/or insert an object using Linq to SQL, these methods work fine but then I get the following exception when it hits the Save() method
System.ArgumentNullException was caught
Message="Value cannot be null. Parameter name: source"
ParamName="source"
Source="System.Data.Linq"
StackTrace:
at System.Data.Linq.ChangeProcessor.SendOnValidate(MetaType type, TrackedObject item, ChangeAction changeAction)
at System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list)
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()
at ilaTraining.TrainingRepository.Save() in C:\Users\kevin\Documents\Visual Studio 2008\Projects\ilaTraining\ilaTraining\Models\TrainingRepository.vb:line 394
at ilaTraining.AdminController.CreateCourseTitle(t_courseTitle title) in C:\Users\kevin\Documents\Visual Studio 2008\Projects\ilaTraining\ilaTraining\Controllers\AdminController.vb:line 433
The object I am passing into the insertOnSubmit or updateOnSubmit methods is fully formed and doesn't break referential integrity as far as I can tell. All the values which are non nulls are filled etc.
I thought it might have been the connection string or something like that but if I manually put information into the database the application can retrieve that. Just not change it.
This is driving me nuts, so if any kind soul out their wishes to put me out of my misery then please do so. Thanks for any/all help and apologies to any moderators I may have upset by posting this in the wrong place.
Thanks

Why am I getting a "Unable to update the EntitySet because it has a DefiningQuery..." exception when trying to update a model in Entity Framework?

While updating with the help of LINQ to SQL using Entity Framework, an exception is thrown.
System.Data.UpdateException: Unable to update the EntitySet 't_emp' because it has
a DefiningQuery and no <UpdateFunction> element exists in the
<ModificationFunctionMapping>
The code for update is :
public void Updateall()
{
try
{
var tb = (from p in _te.t_emp
where p.id == "1"
select p).FirstOrDefault();
tb.ename = "jack";
_te.ApplyPropertyChanges(tb.EntityKey.EntitySetName, tb);
_te.SaveChanges(true);
}
catch(Exception e)
{
}
}
Why am I getting this error?
The problem was in the table structure. To avoid the error we have to make one primary key in the table. After that, update the edmx. The problem will be fixed
Three things:
Don't catch exceptions you can't handle. You're catching every exception possible, and then doing nothing with it (except swallowing it). That's a Bad Thing™ Do you really want to silently do nothing if anything goes wrong? That leads to corrupted state that's hard to debug. Not good.
Linq to SQL is an ORM, as is Entity Framework. You may be using LINQ to update the objects, but you're not using Linq to SQL, you're using Entity Framework (Linq to Entities).
Have you tried the solution outlined here? The exception you posted is somewhat cut off, so I can't be sure it's exactly the same (please update your post if it isn't), and if it is the same, can you comment on whether or not the following works for you?
"[..] Entity Framework doesn't know whether a given view is updatable
or not, so it adds the <DefiningQuery> element in order to safeguard
against having the framework attempt to generate queries against a
non-updatable view.
If your view is updatable you can simply remove the <DefiningQuery>
element from the EntitySet definition for your view inside of the
StorageModel section of your .edmx, and the normal update processing
will work as with any other table.
If your view is not updatable, you will have to provide the update
logic yourself through a "Modification Function Mapping". The
Modification Function Mapping calls a function defined in the
StorageModel section of your .edmx. That Function may contain the
name and arguments to a stored procedure in your database, or you can
use a "defining command" in order to write the insert, update, or
delete statement directly in the function definition within the
StorageModel section of your .edmx." (Emphasis mine, post formatted for clarity and for Stack Overflow)
(Source: "Mike" on MSDN)
But You can Set primary Key in Model if use MVC Asp.net
Just Open model.edmx in your table ,go to your field property and set Entity Key = True

MVC Model Error on TryUpdateModel()

I have an error (see below). At first glance it seems obvious to me, however. I've checked everything: the MODEL is ok; metadata class set ok and i've checked my controller and at the time 'TryUpdateMOdel' is called all is well and the object is as i expect it to be. I'm thinking this will be something silly but been stuck all day, anyone recommend anything?
The associated metadata type for type 'Lms.Model.PaymentFrequency' contains the following unknown properties or fields: SiteAgreementId, PaymentTypeId, PaymentCategoryId, ObligationStartDate, TerminationDate, Comments. Please make sure that the names of these members match the names of the properties on the main type.
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.InvalidOperationException: The associated metadata type for type 'Lms.Model.PaymentFrequency' contains the following unknown properties or fields: SiteAgreementId, PaymentTypeId, PaymentCategoryId, ObligationStartDate, TerminationDate, Comments. Please make sure that the names of these members match the names of the properties on the main type.
Source Error:
Line 120: PaymentFrequency paymentFrequency = this._siteRepository.GetPayment(Convert.ToInt16(collection["PaymentId"])).PaymentFrequency;
Line 121:
Line 122: TryUpdateModel(paymentFrequency);
Line 123:
Line 124: if (!ModelState.IsValid)
It sounds like the metadata class you have attached to your PaymentFrequency model may have properties the model itself doesn't.

Resources