现在的位置: 首页 > 综合 > 正文

EntityFramework Codefirst搭建

2018年04月25日 ⁄ 综合 ⁄ 共 1797字 ⁄ 字号 评论关闭


最近在搭建EF框架,发现没有适合菜鸟学习的(本人菜鸟,遇到很多问题),现在已经搭建成功,先将搭建过程记录下来

1.首先新建一个WEB窗体应用程序

2.添加一个新建项目

3.新建一个类库

4.重复步骤三,项目名称为DataBaseModel

5.添加引用

找到项目DataBase中的引用右键->添加引用->项目->DataBaseModel

找到项目EntityF 右键->添加引用->项目->DataBaseModel + DataBas

6.安装EF

在程序包管理器控制台中输入

Install-Package EntityFramework

在引用中选择管理NUGet程序包

点击安装即可

同样的步骤检查三个项目是否都已安装

到现在为止,EF已经装好,三个层次也被分出来了

现在我们开始编码

using DataBaseModel;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBase
{
    public class DataBaseContext:DbContext
    {
        public DataBaseContext()
            : base("default")
        { }
        public DbSet<User> UserContext { get; set; }
    }
    
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataBaseModel
{
    public class User
    {
        [Key]
        [Display(Name = "ID")]
        public int ID { get; set; }
        public string name { get; set; }
    }
}

配置站点配置文件Web.config

 <connectionStrings>
   <add name="default" connectionString="Data Source=.;Initial Catalog=test;Integrated Security=True;User ID=sa;Password=123;" providerName="System.Data.SqlClient" />
 </connectionStrings>

在项目 EntityF中新加一个web窗体,由于只是教程,在这里仅仅是放了一个Button

代码

using DataBase;
using DataBaseModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EntityF
{
    public partial class test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }
        protected void btn_click(object sender, EventArgs e)
        {
            DataBaseContext db = new DataBaseContext();
            User LXM = new User()
            {
                ID = 12,
                name = "LXM",
            };
            db.UserContext.Add(LXM);
            db.SaveChanges();
        }
    }
}

运行,就能在数据库管理器中看到新建的数据库test

抱歉!评论已关闭.