Get IEnumerable from dbContext

asp.net-core dbcontext entity-framework-core

Question

I have following database class

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;
        }

    }
}

But after call

_database.BrandCategories();

I am getting

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.'

What is the preferred way of getting select lists from database via EF Core ? Do i need to create POCO class for each table and after getting data convert the POCO class into SelectListItem collection ?

1
-1
8/7/2018 2:57:26 PM

Accepted Answer

You can only map to entity types via FromSql, i.e. types that belong to your context. However, once there, you can use LINQ's Select to map to something like SelectListItem:

var items = categories.Select(x => new SelectListItem { Value  x.Id, Title = x.Name });
1
8/7/2018 3:02:19 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow