我有以下数据库课程
namespace Project.Web.Repository
{
public class Database : DbContext
{
public Database(DbContextOptions<Database> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public virtual DbSet<SelectListItem> SelectListItem {get; set;}
public IEnumerable<SelectListItem> Categories()
{
var query = "SELECT Id as [Value], Name as [Text] FROM enum.Category";
IEnumerable<SelectListItem> items = SelectListItem.FromSql(query).ToList<SelectListItem>();
return items;
}
}
}
但是打电话后
_database.BrandCategories();
我得到了
Exception has occurred: CLR/System.InvalidOperationException
An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code: 'The entity type 'SelectListGroup' requires a primary key to be defined.'
通过EF Core从数据库获取选择列表的首选方法是什么?我是否需要为每个表创建POCO类,并在获取数据后将POCO类转换为SelectListItem集合?
答案 0 :(得分:1)
您只能通过FromSql
映射到实体类型,即属于您上下文的类型。但是,一旦到达那里,就可以使用LINQ的Select
映射到类似SelectListItem
的地方:
var items = categories.Select(x => new SelectListItem { Value x.Id, Title = x.Name });