The Weird and The Wonderful
The Weird and The Wonderful forum is a place to post Coding Horrors,
Worst Practices, and the occasional flash of brilliance.
We all come across code that simply boggles the mind. Lazy kludges, embarrasing mistakes, horrid
workarounds and developers just not quite getting it. And then somedays we come across - or write -
the truly sublime.
Post your Best, your worst, and your most interesting. But please - no
programming questions . This forum is purely for amusement and discussions on code snippets. All
actual programming questions will be removed.
|
|
 |

|
I wrote this little workaround earlier this year. EF complains about an insert where ParentId is set, but allows me to set it with an update.
using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
if (newProject.ParentId != null)
{
int parentId = newProject.ParentId.Value;
newProject.ParentId = null;
_projectRepository.Insert(newProject);
newProject.ParentId = parentId;
_projectRepository.Update(newProject);
}
else
{
_projectRepository.Insert(newProject);
}
scope.Complete();
}
|
|
|
|

|
Assuming this is a SQL Server connection, I don't think you can lay this directly at SQL's door, but you might want to see if triggers are involved and see what they do on insert/update. Maybe the update trigger on the child will insert the parentID in the parent table if it doesn't exist?
No, that doesn't make sense, the update should fail with a foreign key constraint failure before it reaches the trigger.
So, when it complains, what is its complaint?
|
|
|
|

|
Something long winded about referential integrity.
|
|
|
|

|
Brady Kelly wrote: Something long winded What else is new with SQL?
|
|
|
|

|
Do you have an insert trigger behind this table in the database by any chance? It would seem to be consistent.
|
|
|
|

|
No. The table is created by EF Code First, nothing but the table itself. Not even indexes but for the PK. I think it's something to do with EF trying to also save another child of the same parent, and clashing somewhere far away.
|
|
|
|
|

|
with EF, it helps you out and takes care of all the FK IDs for you You can fill the nested object and let it handle all the FKs (don't even set the ID properties)
ie:
parentObject.Project = newProject;
_projectRepositroy.Insert(parentObject);
|
|
|
|

|
EF should do that, but somewhere something is amiss - probably my fluent mappings - and I had to resort to the manual update you see in the code excerpt.
|
|
|
|
 |
|
|
General
News
Suggestion
Question
Bug
Answer
Joke
Rant
Admin