Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting this "Invalid object name 'dbo.*'" error with MVC4?

I get this error:

Invalid object name 'dbo.ImageMetas'.

On this line:

return View(db.Images.ToList());

Where my database context looks like this:

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

    public DbSet<ImageMeta> Images { get; set; }
    public DbSet<ImageFile> ImageFiles { get; set; }
}

And my model:

public class ImageMeta
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public UserProfile User { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ImageFile> Files { get; set; } 
}

It's a brand new MVC4 project. I wrote the models first, then auto-generated the controller.

I inspected the database, and indeed the table is missing.

I was under the impression that it would auto-create the table for me though; as this tutorial suggests.

So why isn't it doing that?


Okay, if I add a connection string named after my context (and remove the base constructor), it works now. Why can't I use the DefaultConnection, then?

<add name="GalleryContext"
   connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\gallery.mdf;Integrated Security=True"
   providerName="System.Data.SqlClient"
/>
like image 948
mpen Avatar asked Jan 29 '26 11:01

mpen


1 Answers

Try putting non-existing database in connection string. EF Code-First will create database if it does not exist by default (of course, if credentials provided have rights to create database), but it will not change existing database (because it may affect your existing data).

Changes to existing database are meant to be done using code first migrations.

EDIT:

Alternatively, if you don't care about data at all, you can set database initializer (i.e. in global.asax application start) which drops and recreates database every time you change your model:

DbDatabase.SetInitializer<MyDBContext>(new DropCreateDatabaseIfModelChanges<MyDBContext>());

See DropCreateDatabaseIfModelChanges Class for more details.

like image 78
Goran Obradovic Avatar answered Jan 31 '26 15:01

Goran Obradovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!