English 中文(简体)
数据库中没有绘制地图的表格
原标题:Tables with mapping not being created at the database

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.

我如何在我的设想中开展工作?

我要解释一下我迄今所做的工作:

以下这一方法被认为压倒了制作地图和表格。

PS:Generics. InvokeGenericMethod is a means I established and it s working. 它说的是:

    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);
        }
    }

不工作的部分是我使用《原则和规则》。 结构构成是我为每个类别制定的一种方法,这一方法在绘制地图时与数据库相仿。

这里有一个例子(在这种情况下,接收者有许多信息和信息,许多接收者/许多接触者协会):

PS:我留下评论的代码,这样你就可以看到我尝试的另一种做法。

    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);
    }

this.Database.Initialize(false);被称作我有这个错误:

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:GaiaGaia.RepositoryGaiaContext.cs:line 37
   at Hermes.HMail.SendMessage(Int64 sender, Int64[] toUsers, String subject, String content, FileStream attachment) in G:GaiaHermesHMail.cs:line 78
   at Gaia.Controllers.ApplicationController.Test() in G:GaiaGaiaControllersApplicationController.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)

任何想法?

感谢。

最佳回答

首先,我在EF Book pg.57中看到,任何在线配置都只应在模型设计师所增加的所有配置之后出现。 检查你的法典。

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);
     }
} 
问题回答

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





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签