Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbContext.set() cannot create a DbSet for entity because this type is not included in the model for the context

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

enter image description here

Why it is requiring me to add the MediaDate class to the DbContext class?

Please help what I am doing wrong?

like image 804
yogihosting Avatar asked May 10 '18 15:05

yogihosting


People also ask

Is DbSet part of DbContext?

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.

What is the difference between DbSet and DbContext?

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.

What is IdentityDbContext?

IdentityDbContext() Initializes a new instance of the IdentityDbContext class. IdentityDbContext(DbContextOptions) Initializes a new instance of IdentityDbContext.


2 Answers

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

like image 70
Saurabh Raoot Avatar answered Sep 26 '22 02:09

Saurabh Raoot


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();
}
like image 27
BusyBee Avatar answered Sep 22 '22 02:09

BusyBee