一、获取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.数据库表信息
CREATE TABLE [dbo].[T_EF]
(
[ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL primary key,
[Name] [nchar](10) NULL,
[Age] [tinyint] NULL,
[Location] [nchar](10) NULL
)
2. DbContext
namespace EFConsole
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class BridgeContext : DbContext
{
/// <summary>
/// 利用连接字符串连接数据库
/// </summary>
public BridgeContext(string connStr) : base(connStr)
{
}
/// <summary>
/// 利用App.config中配置的字符串连接数据库
/// </summary>
public BridgeContext() : base("name=BridgeDb")
{
}
public virtual DbSet<T_EF> T_EF { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<T_EF>()
.Property(e => e.ID)
.HasPrecision(18, 0);
modelBuilder.Entity<T_EF>()
.Property(e => e.Name)
.IsFixedLength();
modelBuilder.Entity<T_EF>()
.Property(e => e.Location)
.IsFixedLength();
}
}
}
3.App.config文件
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<!--选择生成带密码时的连接字符串-->
<add name="BridgeDb" connectionString="Server=.;Initial Catalog=Bridge;User ID=sa;Password=123" providerName="System.Data.SqlClient" />
<!--选择生成不带密码时的连接字符串-->
<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" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
4.表文件
namespace EFConsole
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
/// <summary>
/// 指定表名
/// </summary>
[Table("T_EF")]
public class T_EF
{
/// <summary>
/// [主键(每个表必须要有主键),表示是自增列]
/// </summary>
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public decimal ID { get; set; }
/// <summary>
/// [指定对应的列名,限定列的字符长度]
/// </summary>
[Column("Name"), StringLength(10)]
public string Name { get; set; }
/// <summary>
/// 可空类型指定
/// </summary>
public byte? Age { get; set; }
[StringLength(10)]
public string Location { get; set; }
}
}
四、对数据库的增删改查
1.增
using (var bridgeContext = new BridgeContext())
{
//添加一个对象
T_EF t_EF = bridgeContext.T_EF.Add(new T_EF() { Name = "RB" });
//将修改后的保存到数据库
bridgeContext.SaveChanges();
}
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();