实体框架Code First和无效对象名称错误

5
我有一张名为ImporterState的复合表,它与名为Importer和State的表相关联。错误发生在这里context.Importers.Include(q => q.States)。为什么会发生这种情况?
{"无效的对象名称“ImporterStates”。"}
    [Table("HeadlineWebsiteImport", Schema = "GrassrootsHoops")]
        public class Importer
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string RssUrl { get; set; }
            public string Type { get; set; }
            public string Keywords { get; set; }
            public bool Active { get; set; }
            public DateTime DateModified { get; set; }
            public DateTime DateCreated { get; set; }

            public int WebsiteId { get; set; }

            public HeadlineWebsite Website { get; set; }

            [InverseProperty("Importers")]
            public ICollection<State> States { get; set; }
        }

[Table("State", Schema = "GrassrootsHoops")]
    public class State
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Abbr { get; set; }

        [InverseProperty("States")]
        public ICollection<Headline> Headlines { get; set; }

        [InverseProperty("States")]
        public ICollection<Importer> Importers { get; set; }
    }

EF可能指的是你在“dbo”架构中的连接表ImporterStates。请查看此答案 - Eranga
我想处理所有的属性而不是那个方法。但是它确实在我的联结表中做了某些事情,但我没有在代码中引用它。 - Mike Flynn
基于属性的配置非常有限。 - Eranga
好的,我会查看另一条路径。 - Mike Flynn
1个回答

9
许多对许多的关系无法仅使用属性来实现。请尝试使用类似以下的方法:
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Importer>()
            .HasMany(i => i.States)
            .WithMany(s => s.Importers)
            .Map(m =>
                {
                    m.MapLeftKey("ImporterId");
                    m.MapRightKey("StateId");
                    m.ToTable("ImporterState");
                });
    }

完美,我来到这里是因为EF6自动处理了我继承的代码库中的许多对多关系。所以有一天它崩溃了,并开始抱怨一个不存在的表。仔细查看表格,发现它把表名搞反了,前后颠倒了。解决方法是像上面回答的那样明确指定关系。 - IbrarMumtaz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接