Question

I am using MVP, with EntityFramework and an implementation of Castle Windsor.

Everything seems fine however when adding a new record into a table (which has a number of Foreign Keys mapping it to other tables), using dbContext.SaveChanges(), the EntityFramework seems to go on and attempt inserting records in every other table with a foreign key in the immediate table.

For example: Employee table has a foreign key which is linking it to the Department table. When EF is asked to SaveChanges() on the Employee table; it goes on to insert an empty record in the Department table, which is not required and this is triggering this exception:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

I have 'catched' the details of this exception using this:

            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        //For QuickWatch
                        //((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors.First().ValidationErrors.First().ErrorMessage
                    }
                }
            }

The problem seemed to be happening at the time of saving changes; when Windsor Castle has already instantiated 'objects' for every entity. These instances are making EF think that they're there to be saved into the db, which is causing validation error since there no data is being sent into any of these tables.

What can I do to solve this problem. Will creating a base class for the Entity Model help? and if yes, how can I do that?

Please let me know. Thanks.

Update

@Steven Dependencies are not being injected into entities. Entities are being injected into the Presenters (in the constructor). What is happening is that because Deparment has a 'Navigation Property' in Employee, everytime I insert a new employee EntityFramework inserts a blank department with it (in the Department table) and thus generating the validation exception, because no data is being sent for the Department obviously!

Was it helpful?

Solution

Castle Windsor does implicit property injection by default, which means that it will try to inject every public property on the type that's being created. When an Employee has a Department property, it will try to create a Department instance and if it succeeds, it will inject it into that property. This is clearly what's happening here.

You should use your IoC container only for building up object graphs of services, not entities. Don't do that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top