locked
An exception of type 'System.NotSupportedException' occurred in EntityFramework.dll but was not handled in user code RRS feed

  • Question

  • User-1298832285 posted

    I Controller as follow:

        public class HomeController : Controller
        {
            //
            // GET: /Home/
    
            MusicStoreEntities storeDB = new MusicStoreEntities();
    
            public ActionResult Index()
            {
                // Get most popular albums
                var albums = GetTopSellingAlbums(5);
    
                return View(albums);
            }
    
            private List<Album> GetTopSellingAlbums(int count)
            {
                // Group the order details by album and return
                // the albums with the highest count
    
                return storeDB.Albums
                    .OrderByDescending(a => a.OrderDetails.Count())
                    .Take(count)
                    .ToList();
    
                //using (var ctx = new MusicStoreEntities())
                //{
                //    ctx.Albums.Load();
                //    return new List<Album>(storeDB.Albums.Local);
                //}
    
            }
        }

    Error:

    Server Error in '/' Application.
    
    Model compatibility cannot be checked because the DbContext instance was not created using Code First patterns. DbContext instances created from an ObjectContext or using an EDMX file cannot be checked for compatibility.
    
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
    
    Exception Details: System.NotSupportedException: Model compatibility cannot be checked because the DbContext instance was not created using Code First patterns. DbContext instances created from an ObjectContext or using an EDMX file cannot be checked for compatibility.
    
    Source Error: 
    
    
    Line 34:             using (var ctx = new MusicStoreEntities())
    Line 35:             {
    Line 36:                 ctx.Albums.Load();
    Line 37:                 return new List<Album>(storeDB.Albums.Local);
    Line 38:             }

    any idea how I could get rid of this error? I am trying to run the music store sample http://www.asp.net/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-1

    . The example was developed using EF5, hence not compatible with EF6. I recreated the databases, and used database first in to order to get the edm right. And now I'm facing another hurdle as above. My aim is to be able to run this sample in EF6, VS 2015. Thanks a lot.

    Thursday, March 24, 2016 2:58 PM

All replies

  • User-271186128 posted

    Hi Bhupinder Singh,

    According to your code, I'm not sure why you are using the Load method and the local. If you want to query the Albums table, you could refer to the following code:

                List<Album> list = new List<Album>();
                using (var ctx = new MusicStoreEntities())
                {
                   // ctx.Albums.Load();
                    list = ctx.Albums.ToList();
                    return list;
                }

    Best regards,
    Dillion

    Friday, March 25, 2016 8:18 AM
  • User-1298832285 posted

    Thanks for the reply,

    I'm still getting the same error:

    https://onedrive.live.com/redir?resid=1661801353F0F86B!2946&authkey=!AC504BfiiVPcx9w&v=3&ithint=photo%2cPNG

    error

    Tuesday, March 29, 2016 1:13 PM
  • User-1298832285 posted

    One additional thing that I found is that when I comment out the following then it works, but doesn't display the data.

            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new HandleErrorAttribute());
            }
    
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                );
    
            }
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
    
                //System.Data.Entity.Database.SetInitializer(new MvcMusicStore.Models.SampleData());
    
                //AreaRegistration.RegisterAllAreas();
    
                //RegisterGlobalFilters(GlobalFilters.Filters);
                //RegisterRoutes(RouteTable.Routes);
            }
        }

    I thing there was be something wrong with the way the data is retrieved. 

    Tuesday, March 29, 2016 4:08 PM
  • User-271186128 posted

    Hi Bhupinder Singh,

    I suggest you could refer to the following code to set the DB Initializer.

    public class SchoolDBContext: DbContext 
    {
            
        public SchoolDBContext(): base("SchoolDBConnectionString") 
        {
            Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>());
    
            //Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());
            //Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>());
            //Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer());
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
    }
    
    public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext>
    {
        protected override void Seed(SchoolDBContext context)
        {
            IList<Standard> defaultStandards = new List<Standard>();
    
            defaultStandards.Add(new Standard() { StandardName = "Standard 1", Description = "First Standard" });
            defaultStandards.Add(new Standard() { StandardName = "Standard 2", Description = "Second Standard" });
            defaultStandards.Add(new Standard() { StandardName = "Standard 3", Description = "Third Standard" });
    
            foreach (Standard std in defaultStandards)
                context.Standards.Add(std);
    
            base.Seed(context);
        }
    }

    More details, see:

    http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx

    http://www.entityframeworktutorial.net/code-first/seed-database-in-code-first.aspx

    Besides, you could also refer to these links:

    http://stackoverflow.com/questions/19923414/asp-net-seeding-db-entity-framework-is-not-working

    https://social.msdn.microsoft.com/Forums/en-US/558163f0-d4be-43a7-aac3-2df339578e28/entity-framework-41-aspnet-mvc3-seeding-database-does-not-work

    Best regards,
    Dillion

    Wednesday, March 30, 2016 5:56 AM
  • User-1298832285 posted

    Thanks Zhi,

    Since, I'm using Database First for a sample which used code first I was getting error. I have inserted the data into database like so:

      ctx.Albums.Add(
                     new Album { Title = "The Best Of Men At Work", Genre = genres.Single(g => g.Name == "Rock"), Price = 8.99M, Artist = artists.Single(a => a.Name == "Men At Work"), AlbumArtUrl = "/Content/Images/placeholder.gif" });
                    ctx.Albums.Add(new Album { Title = "A Copland Celebration, Vol. I", Genre = genres.Single(g => g.Name == "Classical"), Price = 8.99M, Artist = artists.Single(a => a.Name == "Aaron Copland & London Symphony Orchestra"), AlbumArtUrl = "/Content/Images/placeholder.gif" });
    
    
          ctx.SaveChanges();

    In this way, my database would have the required data and it works somewhat. 

    Wednesday, March 30, 2016 1:21 PM
  • User-1768369891 posted

    hi bhupinder 

    See your error message you got your solution with in error like you got message  

    model compatibility cannot be checked because the DbContext instance was not created using Code First patterns. DbContext instances created from an ObjectContext or using an EDMX file cannot be checked for compatibility.
    

     noted the point "DbContext instance was not created"  you got this message becoz you don't initialize your db context or you define wrong connection suggest you to fix your 

    context instead of other first if you not get what i want to tell you, you just share your conext code like.      

     

    Saturday, April 2, 2016 4:45 AM