问题
I am very new to the Entity Framework. Tried to save an object and it fails with the message
error in saving entities which do not make foreign key properties available
As something wrong happens when EF tries writing to the database, I wanted to see the actual query it is trying to execute. I am not yet using EF 6, so I can't use context.Database.Log. Some search told me that there is a library called Clutch Diagnostics which will help me.
I installed it from NuGet and set it up as described in this blog post. Basically, it involved adding the methods
public void CommandFailed(DbTracingContext context)
{
Debug.WriteLine("\nFAILED\n " + context.Command.CommandText);
// or Trace.WriteLine("\nFAILED\n " + context.Command.CommandText);
}
public void CommandExecuted(DbTracingContext context)
{
Debug.WriteLine("\nExecuted\n " + context.Command.CommandText);
// or Trace.WriteLine("\nExecuted\n " + context.Command.CommandText);
}
to a class which implements the IDbTracingListener
interface, and adding
// Enable Tracing queries
DbTracing.Enable();
// Adding the listener (implementation of IDbTracingListener)
DbTracing.AddListener(new DbTracingListener());
to the application start method in Global.asax.
I expected to now see the SQL queries in my Debug window. But instead I got

What am I doing wrong? Did I miss something? Are my expectations wrong? Is the debug output the wrong place to look for the query? Is the listener meant to work for saving objects to the database?
My method for saving to the database is very simple,
if (keyword.ExtractedKeywords_ID == 0)
{
context.ExtractedKeywords.Add(keyword);
}
else
{
ExtractedKeyword dbEntry = context.ExtractedKeywords.Find(keyword.ExtractedKeywords_ID);
if (dbEntry != null)
{
dbEntry.CorrectSpelling = keyword.CorrectSpelling;
dbEntry.Embryonen = keyword.Embryonen;
dbEntry.ExcelNumber = keyword.ExcelNumber;
dbEntry.IsCell = keyword.IsCell;
dbEntry.IsOrgan = keyword.IsOrgan;
dbEntry.IsRecombinase = keyword.IsRecombinase;
dbEntry.IsReporter = keyword.IsReporter;
dbEntry.IsResearchTopic = keyword.IsResearchTopic;
dbEntry.ModificationStatus = keyword.ModificationStatus;
dbEntry.OriginalSpelling = keyword.OriginalSpelling;
dbEntry.Synonym = keyword.Synonym;
}
}
context.SaveChanges();
I have only tried it with brand-new objects (the if part gets executed), because I don't yet have any entries in the database table for going into the else part.
来源:https://stackoverflow.com/questions/20995098/how-to-use-clutch-for-debugging-sql-statements-executed-by-the-entity-framework