我创建了名为"分配"的模型,但是当我运行添加迁移"交易分配"时,使用 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; }
}
您是否添加了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;}
编辑:感谢科林的评论,您不必添加[Key]
注释,因为AllocationId
在正确的 Id 约定中,该约定将作为键处理。
在为新表添加任何迁移时,请确保还应在 DbContext 中添加模型类。例如。对于分配模型,我添加了
public DbSet<Allocation> Allocation { get; set; }
在 DbContext 中,但后来我收到"不一致的可访问性"错误,然后我只是从 DbSet 代码中删除了"public"关键字。现在代码变成
DbSet<Allocation> Allocation { get; set; }
现在它工作正常。