EF CodeFirst创建数据库


  1. 创建数据模型 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

参考连接 :

    https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing#add-dto-classes

https://www.cnblogs.com/libingql/p/3351275.html

https://www.cnblogs.com/chenwolong/p/CodeFirstDB.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值