-
创建数据模型 Model
namespace RestFulRoute.Models
{
public class Book
{
public int BookId { get; set; }
[Required]
public string Title { get; set; }
public decimal Price { get; set; }
public string Genre { get; set; }
public DateTime PublishDate { get; set; }
public string Description { get; set; }
public int AuthorId { set; get; }
[ForeignKey("AuthorId")]
public Author Author { get; set; }
}
}
namespace RestFulRoute.Models
{
public class Author
{
public int AuthorId { get; set; }
[Required]
public string Name { get; set; }
}
}
2.创建上下文
namespace RestFulRoute.Models
{
public class RestFulRouteContext : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, please use data migrations.
// For more information refer to the documentation:
// http://msdn.microsoft.com/en-us/data/jj591621.aspx
public RestFulRouteContext() : base("name=RestFulRouteContext")
{
}
public System.Data.Entity.DbSet<RestFulRoute.Models.Book> Books { get; set; }
public System.Data.Entity.DbSet<RestFulRoute.Models.Author> Authors { get; set; }
}
}
RestFulRouteContext继承自DbContext,代表一个数据库,RestFulRouteContext有两个属性,代表两个表,这两个表中的属性各自对应的Model中的成员属性
3.配置连接字符串(web.config)
<connectionStrings>
<add name="RestFulRouteContext" connectionString="Data Source=(local); Initial Catalog=RestFulRouteContext-20181009171123; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|RestFulRouteContext-20181009171123.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
这里的name属性和第二步中的上下文类名称一致 注意:Data Source的值最好是local或者对应本地数据库的名称。如;
4. 在Nuget上初始化数据库
在Nuget控制台上输入add-migration Initial update-database两条命令。
有时需要迁移数据库 在Nuget控制台中输入命令enable-migrations
参考连接 :