【问题标题】:Entity Framework Code First and Invalid Object Name Error实体框架代码优先和无效的对象名称错误
【发布时间】:2011-11-25 01:40:48
【问题描述】:

我有一个名为 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。检查this answer
  • 我想做所有的属性而不是那个方法。但是是的,它正在对我的连接表做一些事情,但我没有在我的代码中的任何地方引用它。
  • 基于属性的配置非常有限
  • 知道了。我会检查另一条路径。

标签: entity-framework ef-code-first


【解决方案1】:

仅使用属性是不可能实现多对多的。

尝试使用类似的东西:

    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 在我继承的代码库上为我自动处理多对多关系。所以有一天它爆炸了,开始抱怨一张不存在的桌子。仔细看表,它的表名弄错了,像从前到后的东西。解决方法是明确指定上面回答的关系。
猜你喜欢
  • 2016-02-18
  • 2016-11-12
  • 2019-07-29
  • 2016-07-08
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多