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 ?
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 });
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments