codefirst and multiple EntityCodeFirstConfig's

Editor
Oct 12, 2011 at 4:52 PM

OK, this one is a little more involved.

I'm trying to do codefirst with 1 runMVC project referencing 2 different Models, CommsModel and RefDataModel. 

The dependency is from CommsModel -> RefDataModel; specifically CommsModel.CommunicationTemplateTranslation -> RefDataModel.Language.

In RunWeb.cs, I've defined two entries for EntityPersistorInstaller:

return new EntityPersistorInstaller
{
CodeFirst = true,
CodeFirstConfig = new[] {
new EntityPersistorInstaller.EntityCodeFirstConfig {
AssemblyName = "RefDataModel", 
DataSource = @".\SqlExpress", 
DatabaseName = "refdatadb"
},
new EntityPersistorInstaller.EntityCodeFirstConfig {
AssemblyName = "CommsModel", 
DataSource = @".\SqlExpress", 
DatabaseName = "commsdb"
}
}
};

When I run this I find that both databases are created, but the commsdb has a Languages table as well as refdatadb. I've double checked that there is no Language class in the CommsModel.

Thx
Dan

Coordinator
Oct 12, 2011 at 4:57 PM
I confess that our experience of doing Code First with multiple database is quite limited. There is an automated test for it in the build, but it is a very limited test. So you're probably pioneering, here, again.

That said, my initial reaction is that what you are trying to do is bound to cause problems because you've got two databases but with, as I understand it, a direct object association between them. Entity Framework definitely can't cope with that scenario - because it can only model associations as foreign keys. The fact that it has duplicated the associated type in one of the databases is not something I would have predicted necessarily, but having read that it did, I'm not entirely surprised.

The way I would handle this, following what I call the 'cluster pattern', is that all associations between entities in different models (and therefore, potentially, peristed in different databases) should be modelled as 'interface associations'. This is described in the manual under:

Adding behaviour to your domain objects - a how-to guide
- Advanced Entity Framework techniques
  - How to handle associations that are defined by an interface rather than a class