C#EF的简单使用

一、获取EF

 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         /// <summary>
11         /// 利用连接字符串连接数据库
12         /// </summary>
13         public BridgeContext(string connStr) : base(connStr)
14         {
15         }
16 
17         /// <summary>
18         /// 利用App.config中配置的字符串连接数据库
19         /// </summary>
20         public BridgeContext() : base("name=BridgeDb")
21         {
22         }
23 
24         public virtual DbSet<T_EF> T_EF { get; set; }
25 
26         protected override void OnModelCreating(DbModelBuilder modelBuilder)
27         {
28             modelBuilder.Entity<T_EF>()
29                 .Property(e => e.ID)
30                 .HasPrecision(18, 0);
31 
32             modelBuilder.Entity<T_EF>()
33                 .Property(e => e.Name)
34                 .IsFixedLength();
35 
36             modelBuilder.Entity<T_EF>()
37                 .Property(e => e.Location)
38                 .IsFixedLength();
39         }
40     }
41 }

3.App.config文件 

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3   <configSections>
 4     <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
 5     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
 6   </configSections>
 7   <connectionStrings>
 8     <!--选择生成带密码时的连接字符串-->
 9     <add name="BridgeDb" connectionString="Server=.;Initial Catalog=Bridge;User ID=sa;Password=123" providerName="System.Data.SqlClient" />
10     <!--选择生成不带密码时的连接字符串-->
11     <add name="BridgeContext" connectionString="data source=PC-20181123XOVS\BRIDGE;initial catalog=Bridge;persist security info=True;user id=sa;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
12   </connectionStrings>
13   <startup>
14     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
15   </startup>
16   <entityFramework>
17     <providers>
18       <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
19     </providers>
20   </entityFramework>
21 </configuration>

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     /// <summary>
10     /// 指定表名
11     /// </summary>
12     [Table("T_EF")]
13     public class T_EF
14     {
15         /// <summary>
16         /// [主键(每个表必须要有主键),表示是自增列]
17         /// </summary>
18         [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
19         public decimal ID { get; set; }
20 
21         /// <summary>
22         /// [指定对应的列名,限定列的字符长度]
23         /// </summary>
24         [Column("Name"), StringLength(10)]
25         public string Name { get; set; }
26 
27         /// <summary>
28         /// 可空类型指定
29         /// </summary>
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.查 

//根据主键查询
T_EF t_EF1 = bridgeContext.T_EF.Find(1);
//根据TSQL查询
DbSqlQuery<T_EF> dbSqlQuery = bridgeContext.T_EF.SqlQuery("select * from [T_EF] where [ID] = {0}", 2);

3.改 

//修改数据,需先查出实体,再修改保存
T_EF t_EF1 = bridgeContext.T_EF.Find(1);
t_EF1.Location = "GD";
bridgeContext.SaveChanges();

4.删 

//删除数据也需先查出后删除再保存
DbSqlQuery<T_EF> dbSqlQuery = bridgeContext.T_EF.SqlQuery("select * from [T_EF] where [ID] = {0}", 2);
bridgeContext.T_EF.RemoveRange(dbSqlQuery);
bridgeContext.SaveChanges();

  

 

posted @ 2020-02-26 10:50  Bridgebug  阅读(18321)  评论(0编辑  收藏  举报