Tip 53 – How to debug EF POCO mapping issues

If you are trying to use POCO classes in EF 4.0, it is relatively easy to run into problems with the mapping from your model to your CLR classes.

If you get any nasty problems here, the best way to get to the bottom of things is to try to explicitly load the metadata for your POCO types.

For example if Product is a POCO type and you are having problems getting it working, you can try this code to see what the problem is:

using (MyContext ctx = new MyContext())
{
ctx.MetadataWorkspace.LoadFromAssembly(
typeof(Product).Assembly,
MappingWarning
);
}

Where MappingWarning could be any action / method that takes a string and returns void, like for example:

public void MappingWarning(string warning)
{
Console.WriteLine(warning);
}

Now when you do this, EF will loop over the types in your assembly trying to see if they map to types in the Conceptual Model, if some reason a CLR type is identified and subsequently disqualified – isn’t a valid match – your action with be called, and in our example the warning will be pumped out to the Console.