I am using EF Core. I am using DbContext.Set()
method but it is giving me the error - "Cannot create a DbSet for 'MediaDate' because this type is not included in the model for the context.'"
Below is my code:
var context = new GoldentaurusContext();
DbSet<MediaDate> set = context.Set<MediaDate>();
mediaDateList = set.FromSql("[dbo].[sp_GetMediaDate]")
.Select(x => new SelectListItem { Text = x.DateText, Value = x.DateValue })
.ToList();
The MediaDate class:
public class MediaDate
{
public string DateText { get; set; }
public string DateValue { get; set; }
}
Why it is requiring me to add the MediaDate class to the DbContext class?
Please help what I am doing wrong?
The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views.
Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.
IdentityDbContext() Initializes a new instance of the IdentityDbContext class. IdentityDbContext(DbContextOptions) Initializes a new instance of IdentityDbContext.
Your DB Context class should be like below.
public partial class DatabaseContext : DbContext
{
public DatabaseContext (string ConnectionString) : base(new DbContextOptionsBuilder().UseSqlServer(ConnectionString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Query<MediaData>();
}
Add your models in the DatabaseContext using model builder. This is how I have resolved this isssue
For EF in DotNet Core 3.1+ make sure you add your non-table entity to the OnModelCreating
override on your DbContext
and call .HasNoKey()
on the fluent API. This will allow you to call a stored procedure using DataContext.Set<MediaData>().FromSqlRaw("dbo.MyStoredProc")
and return your entity list.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MediaData>().HasNoKey();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With