问题
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"
/>
回答1:
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.
回答2:
I experienced this problem and found a solution, which requires that the User Schema in SQL is that of the dbo schema thus the tables are created with dbo. at the beginning of them, problem solved.
I am presuming this is a bug that will need fixed by MS.
回答3:
I also experienced the same issue while using Database first approach. Connection string in my service's/service's host web.config was incorrect. I corrected the connection string and it worked.
来源:https://stackoverflow.com/questions/12239707/why-am-i-getting-this-invalid-object-name-dbo-error-with-mvc4