从dbContext获取IEnumerable <selectlistitem>

时间:2018-08-07 14:57:26

标签: asp.net-core entity-framework-core dbcontext

我有以下数据库课程

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集合?

1 个答案:

答案 0 :(得分:1)

您只能通过FromSql映射到实体类型,即属于您上下文的类型。但是,一旦到达那里,就可以使用LINQ的Select映射到类似SelectListItem的地方:

var items = categories.Select(x => new SelectListItem { Value  x.Id, Title = x.Name });