Im working on a MVC3 project using code first entity framework.
On a webpage a button is pushed.
Part of what happends is that a Sale-object is created to be saved in a database:
var newSale = new Sale
{
Id = Guid.NewGuid(),
Material = material,
Buyer = buyer,
CashOut = null,
Token = response.Token,
TimeStamp = null
};
dataContext.Add(newSale);
dataContext.SaveChanges();
After you will be redirected to another controller function that edits the value of the TimeStamp-property of the Sale object.
var dataContext = FOSDataContextFactory.Create();
var = dataContext.Sales.SingleOrDefault(x => x.Token == tokenId);
if (sale != null)
{
sale.TimeStamp = DateTime.UtcNow;
dataContext.SaveChanges();
}
When im steping through the code using the debugger everything works fine and the TimeStamp – property is changed. But when running the web-application without debugging the code a error occurs:
Validation failed for one or more entities. See
‘EntityValidationErrors’ property for more details.
This is the error that i got:
Entity of type:
Sale_9C4571E6D8D390FBA94D51E54B356016DF8C20533C767502369B99F24C117B5B
in state: Modified – Property: Material, Error: The Material field is
required. – Property: Buyer, Error: The Buyer field is required.
What can be the cause of this problem?
The
MaterialandBuyerproperties of yourSaleentity seem to be navigation properties refering to other entities. And you likely have marked these properties asvirtualwhich means that they get lazily loaded as soon as you access them.If you watch these properties in the debugger you trigger lazy loading when you access them through the property watch window. This does not happen when you just run the application in Release mode. Because the properties seem to be marked as required you get the exception in Release mode because your code does not access the properties and they stay
nullwhich causes the validation exception.You have three options to fix the problem:
Introduce foreign key properties into your model:
When you load the
Saleentity the FK properties get loaded as well and EF will consider the required references as set and validation won’t complain.Load the navigation properties with
Include:Turn off the validation, just for this operation: