1、新建控制台应用程序
2、VS2017 打开程序包管理器控制台(工具--Nuget包管理器--程序包管理器控制台)
3、输入Install-Package EntityFrameWork(VS2013 .NET 4.5建议 Install-Package EntityFrameWork -Version 6.0.0);默认项目一定要选择为新建的控制台应用程序项目***
4、’安装EntityFrameWork成功后,在AppConfig中配置节点添加如下连接数据库代码:
<connectionStrings> <add connectionString="server=127.0.0.1;database=test;uid=sa;pwd=******;" name="Constr" providerName="System.Data.SqlClient" /> </connectionStrings>
5、新建数据库 test 。新建表 UserInfo 数据表 字段分别为
Id 主键 自增 int
Name Nvarchar(50)
Email Nvarchar(50)
Age int
Sql语句如下
USE [test] GO /****** Object: Table [dbo].[UserInfo] Script Date: 2019/11/19 星期二 下午 10:29:42 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[UserInfo]( [Id] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NULL, [Age] [int] NULL, [Email] [nvarchar](50) NULL, CONSTRAINT [PK_UserInfo] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
6、新建实体类 UserInfos
public class UserInfos { public int Id { get; set; } public string Name { get; set; } public int Age{ get; set; } public string Email { get; set; } }
7、新建实体配置类Userinfoconfig
public class Userinfoconfig:EntityTypeConfiguration<UserInfos>
{
public Userinfoconfig() { this.ToTable("UserInfo"); }
}
8、新建自定义的Dbcontext类 myDbContext 继承自DbContext类
public class myDbContext:DbContext { public myDbContext() : base("name=Constr") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); var CurrentAssmbly = Assembly.GetExecutingAssembly(); modelBuilder.Configurations.AddFromAssembly(CurrentAssmbly); } public DbSet<UserInfos> DT_UserInfo { get; set; } }
9、Program.cs 内写测试代码
static void Main(string[] args) { UserInfos user = new UserInfos() { Age=10, Email="9@qq.com", Name="lizh" }; using (myDbContext context = new myDbContext()) { context.DT_UserInfo.Add(user); context.SaveChanges(); } Console.ReadKey(); }
10、如果数据成功写入数据库,则代表简单的Code First搭建完成
’