yogihosting
yogihosting

Reputation: 6332

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?

Upvotes: 8

Views: 17388

Answers (4)

BusyBee
BusyBee

Reputation: 219

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

Upvotes: 6

Saurabh Raoot
Saurabh Raoot

Reputation: 1411

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

Upvotes: 6

Mehrdad Tajdini
Mehrdad Tajdini

Reputation: 121

First, you should introduce your model (MediaDate) to DbContext. add a DbSet<MediaDate> property to your context:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<MediaDate> MediaDates { get; set; }
}

Upvotes: 1

Stijn2210
Stijn2210

Reputation: 884

A simple DatabaseContext would look like this:

using YourProject.Model;
using System.Data.Entity;

namespace YourProject.Data
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext() :
            base("name=YourDatabase")
        {

        }

        public DbSet<MediaData> MediaDates{ get; set; }
    }
}

You always need to include your models in the DatabaseContext to create the DbSets. Make sure you've declared the right namespaces and imported the right ones.

Upvotes: 1

Related Questions