Reputation: 831
I'm building an ASP.NET MVC site using the ADO.NET Entity Framework. I have an entity model that includes these entities, associated by foreign keys:
Report(ID, Date, Heading, Report_Type_ID, etc.)
There is a Create.aspx page for each type of SubReport. The post event method returns a new Sub_Report entity.
Before, in my post method, I followed this process:
This workflow succeeded just fine for a couple of weeks. Then last week something changed and it doesn't work any more. Now instead of the save operation, I get this Exception:
UpdateException: "Entities in 'DIR2_5Entities.ReportSourceSet' participate in the 'FK_ReportSources_ReportSourceTypes' relationship. 0 related 'ReportSourceTypes' were found. 1 'Report_Source_Types' is expected."
The debug visualizer shows the following:
In SQL Profiler the prepared SQL statement looks OK. Can anybody point me to what obvious thing I'm missing?
TIA
Notes: The Report and SubReport are always new entities in this case. The Report entity contains properties common to many types of reports and is used for generic queries. SubReports are specific reports with extra parameters varying by type. There is actually a different entity set for each type of SubReport, but this question applies to all of them, so I use SubReport as a simplified example.
Upvotes: 3
Views: 19079
Reputation: 2852
I got this error when I added the new entity to the context but forgot to add the new entity to its parent's collection in the object graph.
For example:
Pet pet = new Pet();
context.Pets.Add(pet);
// forgot this: petOwner.Pets.Add(pet);
Upvotes: 0
Reputation: 21
I got this error because the table didn't have a primary key, it had a FK reference, but no PK.
After adding a PK and updating the model all is well.
Upvotes: 2
Reputation: 1
I've got the same error because of new object instance which created "behind the scene" in "Added" state. This was not obvious.
Upvotes: 0
Reputation: 19423
I realise I'm late to this, but I had a similar problem and I hacked through it for about 3 hours before I came up with a solution. I'd post code, but it's at home - I can do it later if someone needs it.
Here are some things to check:
From memory, I retrieved my references using the context.GetObjectByKey
method, and then explicitly attached those objects to the context using the context.Attach
method before assigning them to the properties of my original object.
Upvotes: 6
Reputation: 16
This tends to happen if your database tables have a 1 - 1 relationship with each other. In your example reportsourceset expects a reportsorttypes with whatever id it is referencing. I have run into this problem when my relationship is linking two primary keys from opposite tables together.
Upvotes: 0
Reputation: 2329
Check if your ReportSource was loaded with the NoTracking option or if its EntityState == 'Detached'. If so, that is your problem, it must be loaded in the context.
Upvotes: 1