【问题标题】:Adding migration for a new table为新表添加迁移
【发布时间】:2014-03-06 06:16:08
【问题描述】:

我创建了名为“Allocation”的模型,但是当我运行 Add-Migration“Allocation for Deals”时,使用 up() 和 down() 函数打开的迁移文件在函数和表中没有任何查询未在数据库中创建。

我的模型是:-

 class Allocation
    {
        [Display(Name = "ID", ResourceType = typeof(Resources.Resource))]
        public int AllocationId { get; set;}

        [Display(Name = "CountryID", ResourceType = typeof(Resources.Resource))]
        public int CountryId { get; set; }

        [Display(Name = "RightID", ResourceType = typeof(Resources.Resource))]
        public int RightId { get; set; }

        [Display(Name = "Amount", ResourceType = typeof(Resources.Resource))]
        public double Amount { get; set; }
    }

【问题讨论】:

    标签: asp.net-mvc entity-framework


    【解决方案1】:

    您添加了DbContext 吗? DbSet?

    public class AllocationContext : DbContext
    {
        public DbSet<Allocation> Allocation { get; set; }
    }
    

    EF 需要知道要生成哪些实体。

    DbContext 通过查看定义的DbSet 属性来确定模型中要包含哪些类。

    您可以将DbSet 行添加到您现有的(如果您已经有)DbContext

    另外注意,你应该在AllocationId上方添加[Key]数据注解:

    [Key]
    [Display(Name = "ID", ResourceType = typeof(Resources.Resource))]
    public int AllocationId { get; set;}
    

    编辑:感谢 Colin 的评论,您不必添加 [Key] 注释,因为 AllocationIdis 在正确的 Id 约定中,将作为键处理。

    【讨论】:

    • 当我在 datacontext 中添加 Dbset 时出现以下错误:--错误 1 ​​可访问性不一致:属性类型“System.Data.Entity.DbSet”的可访问性低于属性 'Assetry.Model.VidZapperDataContext.Allocations' D:\e10\GitHub\assetry\source\Assetry.Model\Model\VidZapperDataContext.cs 146 34 Assetry.Data
    • 公开课程
    • 好答案。但是您不必添加 Key 注释。在没有注释的情况下,按照惯例,EF 将假定名为 Id 的 int 字段是键。
    • Dbset 已经公开。我在 DbContext 中编写了以下代码:-- public DbSet Allocations { get;放; }
    • 还有包含类?见:stackoverflow.com/questions/3992928/…
    【解决方案2】:

    在为新表添加任何迁移时,请确保模型类也应添加到 DbContext 中。例如。对于分配模型,我添加了

    public DbSet<Allocation> Allocation { get; set; }
    

    在 DbContext 中,但后来我收到“不一致的可访问性”错误,然后我刚刚从 DbSet 代码中删除了“public”关键字。现在代码变成了

    DbSet<Allocation> Allocation { get; set; }
    

    现在它可以正常工作了。

    【讨论】:

      猜你喜欢
      • 2015-09-22
      • 1970-01-01
      • 2014-12-26
      • 2021-05-13
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      相关资源
      最近更新 更多