引用网址:
1.打开NuGet程序包管理器控制台

2.选择默认项目(要导入EF的项目),输入命令:Install-Package EntityFramework

3.若导入成功,在引用中会有以下两个引用

二、添加实体数据模型
1.添加新项,选择ADO.NET 实体数据模型

2.选择Code First(也可以选择其他两种模式DB First和Model First)

ps:三者区别,推荐博文:https://blog.csdn.net/u010191243/article/details/44755977?utm_source=copy
3.选择要建立模型的数据库,连接字符串可以选择自动生成或者手动设置

4.选择要生成模型的表和视图

5.项目中会自动生成一个派生于DbContext的文件和各个表模型类

三、生成文件的简单介绍
1.数据库表信息
1 CREATE TABLE [dbo].[T_EF]
2 (
3 [ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL primary key,
4 [Name] [nchar](10) NULL,
5 [Age] [tinyint] NULL,
6 [Location] [nchar](10) NULL
7 )
2. DbContext
1 namespace EFConsole
2 {
3 using System;
4 using System.Data.Entity;
5 using System.ComponentModel.DataAnnotations.Schema;
6 using System.Linq;
7
8 public partial class BridgeContext : DbContext
9 {
10 ///
11 /// 利用连接字符串连接数据库
12 ///
13 public BridgeContext(string connStr) : base(connStr)
14 {
15 }
16
17 ///
18 /// 利用App.config中配置的字符串连接数据库
19 ///
20 public BridgeContext() : base("name=BridgeDb")
21 {
22 }
23
24 public virtual DbSet T_EF { get; set; }
25
26 protected override void OnModelCreating(DbModelBuilder modelBuilder)
27 {
28 modelBuilder.Entity()
29 .Property(e => e.ID)
30 .HasPrecision(18, 0);
31
32 modelBuilder.Entity()
33 .Property(e => e.Name)
34 .IsFixedLength();
35
36 modelBuilder.Entity()
37 .Property(e => e.Location)
38 .IsFixedLength();
39 }
40 }
41 }
3.App.config文件
1 <?xml version="1.0" encoding="utf-8"?>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
4.表文件
1 namespace EFConsole
2 {
3 using System;
4 using System.Collections.Generic;
5 using System.ComponentModel.DataAnnotations;
6 using System.ComponentModel.DataAnnotations.Schema;
7 using System.Data.Entity.Spatial;
8
9 ///
10 /// 指定表名
11 ///
12 [Table("T_EF")]
13 public class T_EF
14 {
15 ///
16 /// [主键(每个表必须要有主键),表示是自增列]
17 ///
18 [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
19 public decimal ID { get; set; }
20
21 ///
22 /// [指定对应的列名,限定列的字符长度]
23 ///
24 [Column("Name"), StringLength(10)]
25 public string Name { get; set; }
26
27 ///
28 /// 可空类型指定
29 ///
30 public byte? Age { get; set; }
31
32 [StringLength(10)]
33 public string Location { get; set; }
34 }
35 }
四、对数据库的增删改查
1.增
1 using (var bridgeContext = new BridgeContext())
2 {
3 //添加一个对象
4 T_EF t_EF = bridgeContext.T_EF.Add(new T_EF() { Name = "RB" });
5 //将修改后的保存到数据库
6 bridgeContext.SaveChanges();
7 }
2.查
1
2
3
4
|
T_EF t_EF1 = bridgeContext.T_EF.Find(1);
DbSqlQuery dbSqlQuery = bridgeContext.T_EF.SqlQuery( "select * from [T_EF] where [ID] = {0}" , 2);
|
3.改
1
2
3
4
|
T_EF t_EF1 = bridgeContext.T_EF.Find(1);
t_EF1.Location = "GD" ;
bridgeContext.SaveChanges();
|
4.删
1
2
3
4
|
DbSqlQuery dbSqlQuery = bridgeContext.T_EF.SqlQuery( "select * from [T_EF] where [ID] = {0}" , 2);
bridgeContext.T_EF.RemoveRange(dbSqlQuery);
bridgeContext.SaveChanges();
|