我是Entityframework的新手。我正在尝试使用entityFramework的Codefirst方法创建数据库。我在DAL层中有我的代码:
[Table("Category")]
public class Category
{
[Key]
public int CategoryId { get; set; }
[Required]
[Column(TypeName="varchar")]
[StringLength(200)]
public string CategoryName { get; set; }
}
public class DatabaseContext:DbContext
{
public DatabaseContext()
: base("DbConnection")
{
//Added the following but still it doesnt work
//Database.SetInitializer<DatabaseContext>(new CreateDatabaseIfNotExists<DatabaseContext>());
}
public DbSet<Category> Categories { get; set; }
}
DAL Layer的App.Config文件中的连接字符串
<connectionStrings>
<add name="DbConnection"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=dbPdtCgry;uid=admin;password=admin123;"
providerName="System.Data.SqlClient"></add>
这不会在Sql server management中创建数据库。但是在App_Data中创建了DbConnection Log file & mdf file
,我可以添加,更新和删除数据。
我在这里错过任何东西吗?
答案 0 :(得分:1)
可能是你错过了连接字符串中的Server = localhost \ SQLserverInstanceName,因为它是在你的App_data上创建的,而不是在SQL服务器的默认文件夹中创建的
答案 1 :(得分:1)
我总是这样一步一步地播种,然后我知道我没有遗漏任何东西。
<connectionStrings>
<add name="LibraryDb" connectionString="Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LibraryDb.mdf;Integrated Security=True; MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
我的课程
public class Author
{
[Key]
public int id { get; set; }
[Required(ErrorMessage = "You Need to Enter A Author Name ")]
public string AuthorName { get; set; }
public string Address { get; set; }
public virtual List<book> books{ get; set; }
}
public class Book
{
public int id { get; set; }
public string BookName { get; set; }
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DateofPublish { get; set; }
public int id { get; set; }
public virtual Author Author{ get; set; }
}
public class LibraryDb: DbContext
{
public DbSet<Author> Authors{ get; set; }
public DbSet<Book> Books{ get; set; }
public LibraryDb() : base("LibraryDb") { }
}
然后在我的Intialiser课程中,我这样做才能播种
public class LibraryInitiliser:DropCreateDatabaseAlways<LibraryDb>
{
protected override void Seed(LibraryDb context)
{
var book= new List<Author>
{
new Author() { AuthorName = "Naame1", Address = "dublin", Book= new List<Book>
{
new Book() { BookName = "Naae1", PublishDate= DateTime.Parse("01/02/1981") },
new Book() { BookName = "Naae1", PublishDate= DateTime.Parse("01/02/1981") },
new Book() { BookName = "Naae1", PublishDate= DateTime.Parse("01/02/1981") }
} },
new Author() { AuthorName = "Naame1", Address = "dublin", Book= new List<Book>
{
new Book() { BookName = "Naae1", PublishDate= DateTime.Parse("01/02/1981") },
new Book() { BookName = "Naae1", PublishDate= DateTime.Parse("01/02/1981") },
new Book() { BookName = "Naae1", PublishDate= DateTime.Parse("01/02/1981") }
} },
} }
};
book.ForEach(m => context.Library.Add(m));
context.SaveChanges();
base.Seed(context);
}
}
并记住global.asax中的添加
Database.SetInitializer(new LandLordInitiliser());
否则不会播种数据。
希望有助于