Entity Framework 学习第一天

时间:2023-03-10 05:06:43
Entity Framework 学习第一天

文章是作为初学者记录之用,没有学习过的同学可以借鉴一下,至于用过和高手嘛,就算了吧。仅是入门。废话不多说了,马上新建个项目,添加Entity Framework,这个词以下将用EF代替。

本文使用的IDE为vs2012。我是新建了一个控制台项目,然后添加的EF,以后我会使用EF作为类库添加到项目中,但这次仅作了解。

Entity Framework 学习第一天

选择Ado.net实体数据模型,文件名随便,我在这里选择了默认名称Model1.edmx,

Entity Framework 学习第一天

在弹出的对话框中选择从数据库生成,这里有个名称叫做dbfirst,就是说数据库先存在,然后根据数据库生成实体模型等。

Entity Framework 学习第一天

选择新建连接,然后选择你要实现的数据库和表,

Entity Framework 学习第一天

表可以选择数据库中的一部分,也可以选择全部,这要看你的需要了,这里只做学习用,所以我只选择了一个user表。点击完成,这过程可能要等一会,因为要导入很多dll。

之后我们会看到一个类似

Entity Framework 学习第一天

uml图,这要归结为vs的强大了,其实edmx文件就是一个xml文档,你可以使用xml打开方式打开这个edmx文件。下面是我的edmx文件

 <?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx">
<!-- EF Runtime content -->
<edmx:Runtime> <!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="remotingModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
<EntityContainer Name="remotingModelStoreContainer">
<EntitySet Name="user" EntityType="remotingModel.Store.user" store:Type="Tables" Schema="dbo" />
</EntityContainer>
<EntityType Name="user">
<Key>
<PropertyRef Name="id" />
</Key>
<Property Name="id" Type="nvarchar" Nullable="false" MaxLength="" />
<Property Name="name" Type="nvarchar(max)" />
<Property Name="pwd" Type="nvarchar(max)" />
<Property Name="department" Type="int" />
<Property Name="status" Type="int" />
<Property Name="registertime" Type="datetime" />
<Property Name="level" Type="nvarchar" MaxLength="" />
<Property Name="cometime" Type="datetime" />
<Property Name="isdel" Type="int" />
<Property Name="balance" Type="money" />
</EntityType>
</Schema>
</edmx:StorageModels> <!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="remotingModel" Alias="Self" p1:UseStrongSpatialTypes="false" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns:p1="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
<EntityContainer Name="remotingEntities" p1:LazyLoadingEnabled="true">
<EntitySet Name="users" EntityType="remotingModel.user" />
</EntityContainer>
<EntityType Name="user">
<Key>
<PropertyRef Name="id" />
</Key>
<Property Name="id" Type="String" Nullable="false" MaxLength="" Unicode="true" FixedLength="false" />
<Property Name="name" Type="String" MaxLength="Max" Unicode="true" FixedLength="false" />
<Property Name="pwd" Type="String" MaxLength="Max" Unicode="true" FixedLength="false" />
<Property Name="department" Type="Int32" />
<Property Name="status" Type="Int32" />
<Property Name="registertime" Type="DateTime" Precision="" />
<Property Name="level" Type="String" MaxLength="" Unicode="true" FixedLength="false" />
<Property Name="cometime" Type="DateTime" Precision="" />
<Property Name="isdel" Type="Int32" />
<Property Name="balance" Type="Decimal" Precision="" Scale="" />
</EntityType>
</Schema>
</edmx:ConceptualModels> <!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs">
<EntityContainerMapping StorageEntityContainer="remotingModelStoreContainer" CdmEntityContainer="remotingEntities">
<EntitySetMapping Name="users">
<EntityTypeMapping TypeName="remotingModel.user">
<MappingFragment StoreEntitySet="user">
<ScalarProperty Name="id" ColumnName="id" />
<ScalarProperty Name="name" ColumnName="name" />
<ScalarProperty Name="pwd" ColumnName="pwd" />
<ScalarProperty Name="department" ColumnName="department" />
<ScalarProperty Name="status" ColumnName="status" />
<ScalarProperty Name="registertime" ColumnName="registertime" />
<ScalarProperty Name="level" ColumnName="level" />
<ScalarProperty Name="cometime" ColumnName="cometime" />
<ScalarProperty Name="isdel" ColumnName="isdel" />
<ScalarProperty Name="balance" ColumnName="balance" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings> </edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<Designer xmlns="http://schemas.microsoft.com/ado/2009/11/edmx">
<Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</Connection>
<Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
<DesignerProperty Name="EnablePluralization" Value="False" />
<DesignerProperty Name="IncludeForeignKeysInModel" Value="True" />
<DesignerProperty Name="CodeGenerationStrategy" Value="无" />
</DesignerInfoPropertySet>
</Options>
<!-- Diagram content (shape and connector positions) -->
<Diagrams></Diagrams>
</Designer>
</edmx:Edmx>

上面我用空行隔出来了三个部分,第一部分就是描述数据库,包括字段,字段类型。第二部分就是实体模型,注意下面的t4模板要用到这个部分。最后部分就是映射文件,也就是将第一部分与第二部分的内容之间的桥。对应关系。

下面我们打开Model1.tt文件,这里如果我们直接打开,效果就是一个txt文本。我们可以安装一个插件,在工具中选择扩展和更新,联机中搜索t4 editor,下载安装,重启vs,重新打开Model1.tt文件就可以看到效果了,这个文件读取之前的edmx文件,遍历edmx实体及实体的属性,生成相应实体的cs文件。我们可以说Model1.tt文件主要的作用就是生成实体文件的。还有一个context.tt文件,从文件名我们可以猜个大概(上下文,我们常常用这个东西操作好多东西),这时我们可以想一下,EF是用来操作数据库的,现在数据实体有了,怎么进行增删改查呢?对,就是这个context。我们这就来看看这个context.cs文件吧,

 namespace EFConsole
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure; public partial class remotingEntities : DbContext
{
public remotingEntities()
: base("name=remotingEntities")
{
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
} public DbSet<user> users { get; set; }
}
}

似乎文件内容好少啊,别急,看父类DBContext,父类的方法很多。

remotingEntities类会将所有的数据实体封装成一个集合,然后让我们操作实体。

下面让我们来看看这个上下文的强大功能吧

简单的增删改查功能

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace EFConsole
{
class Program
{
public static remotingEntities dbContext = new remotingEntities();
static void Main(string[] args)
{ add();
select();
update();
remove();
Console.ReadKey();
} #region 添加方法
/// <summary>
/// 添加方法
/// </summary>
public static void add()
{
int res = -;
user tempData = new user() { name = "test", id = "", balance = };
dbContext.users.Add(tempData);
res = dbContext.SaveChanges();
if (res > )
{
Console.WriteLine("add function:suc");
}
else
{
Console.WriteLine("add function:fail");
}
}
#endregion #region 查询方法
/// <summary>
/// 查询方法
/// </summary>
public static void select()
{
user tempData = dbContext.users.Where(e => e.id == "").FirstOrDefault();
Console.WriteLine("select function:" + tempData.name);
}
#endregion #region 修改方法
/// <summary>
/// 修改方法
/// </summary>
public static void update()
{
int res = -;
user tempData = dbContext.users.Where(e => e.id == "").FirstOrDefault();
Console.WriteLine("before update function:" + tempData.name);
tempData.name = "update name";
res = dbContext.SaveChanges();
if (res > )
{
Console.WriteLine("update function:suc,update data userName is" + tempData.name);
}
else
{
Console.WriteLine("update function :fail");
}
}
#endregion #region 删除方法
/// <summary>
/// 删除方法
/// </summary>
public static void remove()
{
int res = -;
user tempData = dbContext.users.Where(e => e.id == "").FirstOrDefault();
dbContext.users.Attach(tempData);
dbContext.users.Remove(tempData);
res = dbContext.SaveChanges();
if (res > )
{
Console.WriteLine("remove function :suc");
}
else
{
Console.WriteLine("remove function :fail");
}
}
#endregion
}
}

Entity Framework 学习第一天

成功了哦,不信可以去数据库证实一下。

今天就写到这里了,有时间还会将EF当做类库写一个简单的测试。

项目源码