Hello,
Since trying to convert a site over to Asp.Net Core 2.0 I have run into this problem. The viewmodels are not a DB set within the database so using FromSql to call the stored procedures would not work. Now it was my understanding that going to Asp.Net Core 2.1 and EF Core 2.1 that this should in theory work. When I try to debug the site I still get the same message that I had with Asp.Net Core 2.0 and EF Core 2.0 as follows:
InvalidOperationException: Cannot create a DbSet for 'ClassViewModel' because this type is not included in the model for the context.
Here is what I have in my controller:
#region snippet_ContextInController public class ClassesController : Controller { private readonly LotroModel _db; public ClassesController(LotroModel db) { _db = db; } #endregion // GET: Classes public IActionResult Index() => View(_db.Set<ClassViewModel>().FromSql( sql: "SELECT Class_ID AS ClassID, Class_Name AS ClassName FROM dbo.Class WHERE ActiveRecord = 1" ).ToList());
Here is the viewmodel:
public class ClassViewModel { [HiddenInput] public int ClassID { get; set; } [Required] [StringLength(20)] [Display(Name = "Name")] public string ClassName { get; set; } }
I simply want to call the Stored Procedure and get the information for the View without having extra stuff in the database. This worked perfectly fine with the full framework, though using .SqlQuery instead of .FromSql. Everything I have read points me to having the same functionality, at least with EF Core 2.1, unless I am reading it wrong.
An EF Core model can now include query types. Unlike entity types, query types do not have keys defined on them and cannot be inserted, deleted or updated (i.e. they are read-only), but they can be returned directly by queries. Some of the usage scenarios for query types are:
- Mapping to views without primary keys
- Mapping to tables without primary keys
- Mapping to queries defined in the model
-
Serving as the return type for
FromSql()
queries
Any help would be appreciated.