Question

I have looked at past questions on this but I can't solve my problem

I am having problems connecting a simple database to MVC project. This is very difficult to do and I am using VS2010, SQL Server 2008 (remote DB). I have a DB already created and I want to use code first with Entity Framework. Sounds easy as I just follow a tutorial but no tutorial I used has ever worked. The tutorials use older MVC and older Entity Framework. I have MVC4 and EF 5

Here are the steps I am using

  1. create new MVC project and in references I see Entity Framework

  2. create class which will correspond to a table not yet created in the DB

  3. add connection string to web.config

  4. add extra line to global.asax to avoid an error entity 5 throws up (found out about this from other peoples problems with this)

  5. add controller with db and dbcontext

  6. run project and as you could guess a problem occurs with controller called video

Error:

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.videos'.

I have no idea and this MVC seems a lot more unstable than web forms as I can connect to the same DB in webforms without an issue .

 <add  name="videoDBContext"
       connectionString="Data Source=xxxxxxx;Initial Catalog=xx;Persist Security Info=True;User ID=xx;    Password=xxx"
       providerName="System.Data.SqlClient" />

Class:

public class video
{
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}

DBContext:

public class videoDBContext : DbContext
{
    public DbSet<video> videos{ get; set; }
}

Controller action

public ActionResult Index()
    {
        return View(db.videos.ToList()); //
  Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.videos'.
    }
Was it helpful?

Solution

You're connecting to the Database fine. The actual DB model and the codefirst model are not in sync, hence the error.

You're adding a DbSet to the DBContext for video, but no such table exists within your current database. Unless your database initializer states to create the models when it does not exist, this is exactly the error I'd expect you to get.

Also, I see no mapping class defined or mentioned that maps the model class back to the database table.

Take a look at http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application. This gets into database intializers towards the end. The other option is to simply create the table manually.

So, problem one, no database initializer (or pre-defined table). Problem two, no mapping class for the table and OnModelCreating, at least from what you've shown. It's entirely possible that you're not using the fluent api to define your mappings and instead are just using attributes in the video model, but again, you didn't show that, so I'm going to show you the fluent way.

EDIT:

I've updated this code from a test project I created locally with your naming conventions. This 100% works. These are the exact class I created or reverse engineered.

public class videoDBContext : DbContext
{
    static videoDBContext()
    {
        Database.SetInitializer<videoDBContext>(null);
    }

    public videoDBContext()
        : base("Name=videoDBContext")
    {
    }

    public DbSet<Video> Videos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new VideoMap());
    }
}

domain class

public class Video
{
    public int Id { get; set; }
    public string Description { get; set; }
}

and the mapping class

public class VideoMap : EntityTypeConfiguration<Video>
{
    public VideoMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.Description)
            .IsRequired()
            .HasMaxLength(50);

        // Table & Column Mappings
        this.ToTable("Video");
        this.Property(t => t.Id).HasColumnName("Id");
        this.Property(t => t.Description).HasColumnName("Description");
    }
}

and then my controller action

    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        using (videoDBContext context = new videoDBContext())
        {
            var list = context.Videos.ToList();
        }

        return View();
    }

This returns whatever "videos" I added to the table.

As for what goes where, it doesn't really matter if you're doing everything in one project. Pick a spot. Here's how things shook out in mine.

enter image description here

You have to remember there's additional upfront effort when working with code first to get things up and running. Once you get the hang of it however, it's a really nice way of working with databases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top