我似乎无法让EF Code First与SQL Server 2008 R2一起使用。我得到的错误是“无效的对象名称'dbo.Movies'。”
它不会自动创建表格。
我的连接字符串:
<add name="MovieDBContext"
connectionString="Server=(local); Database=Movies; Trusted_Connection=true; Integrated Security=True"
providerName="System.Data.SqlClient" />
我的模型和上下文类:
public class Movie
{
public int ID { get; set; }
[Required(ErrorMessage = "Title is required")]
public string Title { get; set; }
[Required(ErrorMessage = "Date is required")]
public DateTime ReleaseDate { get; set; }
[Required(ErrorMessage = "Genre must be specified")]
public string Genre { get; set; }
[Required(ErrorMessage = "Price Required")]
[Range(1, 100, ErrorMessage = "Price must be between $1 and $100")]
public decimal Price { get; set; }
[StringLength(5)]
public string Rating { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Movie>().Property(p => p.Price).HasPrecision(18, 2);
}
}
非常感谢任何帮助。
答案 0 :(得分:4)
我忘记了默认情况下是否已启用,但请尝试在Application_Start
中进行设置(非常确定不是)
System.Data.Entity.Database.DbDatabase.SetInitializer<MovieDBContext>(new CreateDatabaseIfNotExists<MovieDBContext>());
答案 1 :(得分:1)
继续我目前的设置(用你的详细信息替换上限):
<connectionStrings>
<add name="TITLEContext" connectionString="metadata=res://*/Models.TITLE.csdl|res://*/Models.TITLE.ssdl|res://*/Models.TITLE.msl;provider=System.Data.SqlClient;provider connection string="Data Source=DATASOURCE;Initial Catalog=DATABASE;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
然后我在Public TITLEContext()
中跟进了这个DbDatabase.SetInitializer(new DropCreateDatabaseIfModelChanges<TITLEContext>());
尝试了几次,但在你的一个载荷上设置了断点并检查了上下文的实体。它应该有一个选项来查看数据库连接字符串......
祝你好运!答案 2 :(得分:0)
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
希望有所帮助