0

I've been trying to implement the Repository pattern using EntityFramework5. I already got the basics to work. My repositories are being loaded only when necessary and the data is being inserted/updated/retrieved in the database as it should. The problem is: I can't get the tables with mapping to be correctly created, or even created at all. I've been reading some articles online, even here, talking about ways to work with mapped tables and create them in the database, but I haven't succeed. Hands my question here.

How do I get it to work in my scenario?

I'll explain what I'm doing so far:

This method below is overriden to, supposedly, create the mappings and tables.

PS: Generics.InvokeGenericMethod is a method I created and it's working. It does what it says :)

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        foreach (Type entityType in Repositories.Keys)
        {
            //Invokes the Entity method from DbModelBuilder injecting the class type.
            Generics.InvokeGenericMethod(modelBuilder, typeof(DbModelBuilder), entityType, "Entity", null);
        }

        foreach (GaiaEntityConfiguration config in EntityConfigurations)
        {
            //Defines each mapping existing in the context
            config.SetConfiguration(modelBuilder);
        }
    }

The part that is not working is where I use SetConfiguration. SetConfiguration is a method I created for each class added to the context that has mapping, have that mapping mirrored to the database.

Here's one example (in this case a recipient has many messages and messages have many recipients / many-to-many association):

PS: I left the commented code so you can see one other approach I tried.

    public RecipientEntityConfiguration()
    {
        this.LeftKey = "RecipientId";
        this.RightKey = "MessageId";
        this.Schema = "Hermes";
        this.TableName = "RecipientMessage";
    }

    public override void SetConfiguration(DbModelBuilder modelBuilder)
    {
        //EntityTypeConfiguration<Recipient> entityTypeConfiguration = new EntityTypeConfiguration<Recipient>();

        //entityTypeConfiguration
        //    .HasMany<Message>(r => r.Messages)
        //    .WithMany(m => m.Recipients)
        //    .Map(mr =>
        //    {
        //        mr.MapLeftKey(this.LeftKey);
        //        mr.MapRightKey(this.RightKey);
        //        mr.ToTable(this.TableName, this.Schema);
        //    });
        modelBuilder.Entity<Recipient>()
            .HasMany<Message>(r => r.Messages)
            .WithMany(m => m.Recipients)
            .Map(mr =>
            {
                mr.MapLeftKey(this.LeftKey);
                mr.MapRightKey(this.RightKey);
                mr.ToTable(this.TableName, this.Schema);
            });
        //modelBuilder.Configurations.Add<Recipient>(entityTypeConfiguration);
    }

When this.Database.Initialize(false); is called I get this error:

Value cannot be null.
Parameter name: key

StackTrace:

   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at System.Data.Entity.ModelConfiguration.Configuration.Mapping.SortedEntityTypeIndex.Add(EdmEntitySet entitySet, EdmEntityType entityType)
   at System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Analyze()
   at System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Configure()
   at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
   at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
   at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.Initialize()
   at System.Data.Entity.Database.Initialize(Boolean force)
   at Gaia.Repository.GaiaContext..ctor(GaiaContextConfiguration config) in E:\Gaia\Gaia.Repository\GaiaContext.cs:line 37
   at Hermes.HMail.SendMessage(Int64 sender, Int64[] toUsers, String subject, String content, FileStream attachment) in G:\Gaia\Hermes\HMail.cs:line 78
   at Gaia.Controllers.ApplicationController.Test() in G:\Gaia\Gaia\Controllers\ApplicationController.cs:line 18
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.<>c__DisplayClass1.<WrapVoidAction>b__0(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)

Any ideas?

Thanks.

eestein
  • 4,914
  • 8
  • 54
  • 93
  • it's hard to follow like this as you have a more complex use of EF/CF (not usually done, so you might expect problems if doable). Could you post a working demo/repro, that'd help, otherwise we could just guess. – NSGaga-mostly-inactive Apr 14 '12 at 13:18
  • @NSGaga I understand. That's why I tried to explain everything in detail and say what is working. And answering to your question: the working part is already there... when I call the entity method of each table. The only problem is with the foreach in which I set the configurations. If I remove that, the tables are created, but without the mapping table. If you need more code just let me know what part. Thanks. – eestein Apr 14 '12 at 13:21
  • I understand, just best if I could fast run it locally, and see what's going on - otherwise it's a bit 'abstract' and it's an unusual use - though you could go away with it:). I had something similar done with custom ORM. In short, I'd need the 'whole thing' :) just scaled down to one class/model and just one config modelbuilder set up for it - something that compiles (as much as it does) and produces the error. – NSGaga-mostly-inactive Apr 14 '12 at 13:30
  • @NSGaga I see, that might be kinda hard. As of now I have 10 projects http://img52.imageshack.us/img52/8821/ashampoosnap2012041410h.png and even though I'm doing this project for learning I have some sensitive information spread through the code. Either way, I'm still trying to figure it out by myself. If I can't I guess I'll just have to wait. Thanks again for your time. – eestein Apr 14 '12 at 13:42
  • got that - but you could just cut down the 'technically relevant' piece - i.e. why not just add one entity (test) and your generic invocation - and config problem, 'make the case out of it' - I'm not expecting full code :) no please, just few liners. It might help you understand this better too. np – NSGaga-mostly-inactive Apr 14 '12 at 14:29
  • @NSGaga Ok, I'll try to do that. Thanks for your willingness. Peace. – eestein Apr 15 '12 at 15:33

2 Answers2

2

First of all, I figured out in EF Book pg.57, that any in-line configurations, should appears only after all configurations added to modelbuilder. Checks your code.

Next, try this version of code, for automatiс adding mapping to modelbuilder. The goal is to remove calls from EntityTypeConfigurations and use pure method of adding configurations to context. Move your code from SetConfiguration to constructor and try to use my version. It's worked for me as well.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     var entityMapTypes = assembly.GetTypes().Where(
         (t => t.BaseType != null && t.BaseType.IsGenericType && 
               t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)));

     foreach (var mapType in entityMapTypes)
     {
         dynamic configurationInstance = Activator.CreateInstance(mapType);
         modelBuilder.Configurations.Add(configurationInstance);
     }
} 
1

This is going to be my first answer in stackoverflow, so i hope it helps someone! Turns out EF is a sensitive creature, and it doesn't appreciate entities with properties named "Type", so if you have any, just rename them to something along the lines of "EntityType".

I've also heard about people having similar issues with properties that have an abstract type, just in case someone's issue is not the one i described above, have a look at your properties' types and check whether they're abstract: DbContext fails to initialize Model-first database

Community
  • 1
  • 1
Luis Ferrao
  • 1,463
  • 2
  • 15
  • 30