Pav*_*vel 5 asp.net entity-framework entity-framework-core .net-core asp.net-core
我是 EF Core 的新手,正在尝试播种枚举。
据Data Seeding称,此功能是 EF Core 2.1 的新增功能。
我查看了几个解决方案,包括Blake Mumford 的 SO 解决方案,但这对我不起作用,因为枚举不是引用类型。
我的目标(在迁移的帮助下)是将 Category 枚举填充到名为 Category 的新 SQL 表中,并让我的 Payment 表包含引用 Category 表作为外键的列。
任何帮助将不胜感激。谢谢。
public partial class Payment
{
public int PaymentId { get; set; }
public DateTime PostedDate { get; set; }
public string Vendor { get; set; }
public decimal Amount { get; set; }
public virtual Category Category { get; set; }
}
public enum Category
{
Restaurants,
Groceries,
[Display(Name = "Home Goods")]
HomeGoods,
Entertainment
}
public partial class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Error: The type Category must be a reference type in order to use it as parameter TEntity in the
// genric type or method ModelBuilder.Entity<TEntity>()
modelBuilder.Entity<Category>().HasData(Category.Restaurants,
Category.Groceries,
Category.HomeGoods,
Category.Entertainment);
}
}
Run Code Online (Sandbox Code Playgroud)
您无法将枚举类型的值植入数据库,因为枚举不是实体类型,因此首先不会进入数据库。换句话说,不会有Categories表,因此将值播种到该不存在的表中是没有意义的。
如果您实际上希望将类别保留在数据库中,那么您需要创建一个类,例如:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5278 次 |
| 最近记录: |