【问题标题】:EF code first model not in sync with databaseEF 代码优先模型与数据库不同步
【发布时间】:2015-12-07 05:42:23
【问题描述】:

我的 EF Code First 模型由于某种原因与数据库不同步。我收到此错误:

{"Invalid column name 'Type_Id1'."}

该字段实际上称为“Type_Id”,所以我不确定 1 是从哪里出现的。我有一个名为 Type_Id 的表列,并且我在类型实体模型中添加了一个 Type_Id。

为什么我会收到该错误消息,以及为什么我会在名称末尾收到 1?

更新

我的任务类:

public class Task
    {
        public Task()
        {
            Language = 1;
            Grades = new HashSet<Grade>();
            Categories = new HashSet<Category>();
            Subjects = new HashSet<Subject>();
            Rooms = new Collection<Room>();
            Tools = new Collection<Tool>();
        }

        [Key]
        public int Id { get; set; }

        public string Description { get; set; }

        public virtual TaskType Type { get; set; }

        public string Rules { get; set; }

        [Required]
        [StringLength(200), MinLength(1)]
        public string Name { get; set; }

        public int PreperationTime { get; set; }

        public int InstructionTime { get; set; }

        public int TaskTime { get; set; }

        public int Type_Id { get; set; }

        public string VideoLink { get; set; }

        [Required]
        public int Language { get; set; }

        public int? MinimumParticipants { get; set; }

        public int? MaximumParticipants { get; set; }

        public int? Rating { get; set; }

        [Required]
        public string CreatedBy { get; set; }

        public virtual ICollection<Grade> Grades { get; set; }

        public virtual ICollection<Category> Categories { get; set; }

        public virtual ICollection<Subject> Subjects { get; set; }

        public virtual ICollection<Room> Rooms { get; set; }

        public virtual ICollection<Tool> Tools { get; set; }
    }

DBContext 类:

public ApplicationDbContext() : base("DefaultConnection", false)
        {
        }

        public DbSet<Task> Tasks { get; set; }
        public DbSet<TaskType> TaskTypes { get; set; }


        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

【问题讨论】:

  • 你会为你的模型添加一些代码吗?
  • @Bazinga - 没有真正的模型,这些类拥有 db 结构中的属性,我有 dbcontext 类和所有类的 dbset。如果您需要任何具体的东西,请告诉我。谢谢帮助
  • 至少发布您的 POCO 类的代码,并将您的模型构建器发布到 DbContext 中。
  • @DevilSuichiro 更新

标签: entity-framework ado.net ef-code-first code-first entity-framework-migrations


【解决方案1】:

您需要在导航属性上添加 FK 属性。 EF 正在创建 Type_Id1,因为 Type_Id 已经存在(尽管按照惯例不能判断它是 FK)。

[ForeignKey("Type_Id")] 
public virtual TaskType Type { get; set; }

https://msdn.microsoft.com/en-us/data/jj591583.aspx#Relationships

【讨论】:

  • 其实是FK。我应该删除公共 int Type_Id { get;放; } 我目前有?谢谢
  • 不,你把它留在那里,然后告诉 EF 那是你的 FK,所以它不会创建 Type_Id1
猜你喜欢
  • 2011-07-23
  • 1970-01-01
  • 2012-04-27
  • 2011-04-17
  • 1970-01-01
  • 2018-02-26
  • 2013-03-13
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多