zoukankan      html  css  js  c++  java
  • Entity Framework 学习第一天

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

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

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

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

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

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

    之后我们会看到一个类似

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

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx">
     3   <!-- EF Runtime content -->
     4   <edmx:Runtime>

    5 <!-- SSDL content --> 6 <edmx:StorageModels> 7 <Schema Namespace="remotingModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl"> 8 <EntityContainer Name="remotingModelStoreContainer"> 9 <EntitySet Name="user" EntityType="remotingModel.Store.user" store:Type="Tables" Schema="dbo" /> 10 </EntityContainer> 11 <EntityType Name="user"> 12 <Key> 13 <PropertyRef Name="id" /> 14 </Key> 15 <Property Name="id" Type="nvarchar" Nullable="false" MaxLength="32" /> 16 <Property Name="name" Type="nvarchar(max)" /> 17 <Property Name="pwd" Type="nvarchar(max)" /> 18 <Property Name="department" Type="int" /> 19 <Property Name="status" Type="int" /> 20 <Property Name="registertime" Type="datetime" /> 21 <Property Name="level" Type="nvarchar" MaxLength="50" /> 22 <Property Name="cometime" Type="datetime" /> 23 <Property Name="isdel" Type="int" /> 24 <Property Name="balance" Type="money" /> 25 </EntityType> 26 </Schema> 27 </edmx:StorageModels>

    28 <!-- CSDL content --> 29 <edmx:ConceptualModels> 30 <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"> 31 <EntityContainer Name="remotingEntities" p1:LazyLoadingEnabled="true"> 32 <EntitySet Name="users" EntityType="remotingModel.user" /> 33 </EntityContainer> 34 <EntityType Name="user"> 35 <Key> 36 <PropertyRef Name="id" /> 37 </Key> 38 <Property Name="id" Type="String" Nullable="false" MaxLength="32" Unicode="true" FixedLength="false" /> 39 <Property Name="name" Type="String" MaxLength="Max" Unicode="true" FixedLength="false" /> 40 <Property Name="pwd" Type="String" MaxLength="Max" Unicode="true" FixedLength="false" /> 41 <Property Name="department" Type="Int32" /> 42 <Property Name="status" Type="Int32" /> 43 <Property Name="registertime" Type="DateTime" Precision="3" /> 44 <Property Name="level" Type="String" MaxLength="50" Unicode="true" FixedLength="false" /> 45 <Property Name="cometime" Type="DateTime" Precision="3" /> 46 <Property Name="isdel" Type="Int32" /> 47 <Property Name="balance" Type="Decimal" Precision="19" Scale="4" /> 48 </EntityType> 49 </Schema> 50 </edmx:ConceptualModels>

    51 <!-- C-S mapping content --> 52 <edmx:Mappings> 53 <Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs"> 54 <EntityContainerMapping StorageEntityContainer="remotingModelStoreContainer" CdmEntityContainer="remotingEntities"> 55 <EntitySetMapping Name="users"> 56 <EntityTypeMapping TypeName="remotingModel.user"> 57 <MappingFragment StoreEntitySet="user"> 58 <ScalarProperty Name="id" ColumnName="id" /> 59 <ScalarProperty Name="name" ColumnName="name" /> 60 <ScalarProperty Name="pwd" ColumnName="pwd" /> 61 <ScalarProperty Name="department" ColumnName="department" /> 62 <ScalarProperty Name="status" ColumnName="status" /> 63 <ScalarProperty Name="registertime" ColumnName="registertime" /> 64 <ScalarProperty Name="level" ColumnName="level" /> 65 <ScalarProperty Name="cometime" ColumnName="cometime" /> 66 <ScalarProperty Name="isdel" ColumnName="isdel" /> 67 <ScalarProperty Name="balance" ColumnName="balance" /> 68 </MappingFragment> 69 </EntityTypeMapping> 70 </EntitySetMapping> 71 </EntityContainerMapping> 72 </Mapping> 73 </edmx:Mappings>


    74 </edmx:Runtime> 75 <!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) --> 76 <Designer xmlns="http://schemas.microsoft.com/ado/2009/11/edmx"> 77 <Connection> 78 <DesignerInfoPropertySet> 79 <DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" /> 80 </DesignerInfoPropertySet> 81 </Connection> 82 <Options> 83 <DesignerInfoPropertySet> 84 <DesignerProperty Name="ValidateOnBuild" Value="true" /> 85 <DesignerProperty Name="EnablePluralization" Value="False" /> 86 <DesignerProperty Name="IncludeForeignKeysInModel" Value="True" /> 87 <DesignerProperty Name="CodeGenerationStrategy" Value="" /> 88 </DesignerInfoPropertySet> 89 </Options> 90 <!-- Diagram content (shape and connector positions) --> 91 <Diagrams></Diagrams> 92 </Designer> 93 </edmx:Edmx>

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

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

     1 namespace EFConsole
     2 {
     3     using System;
     4     using System.Data.Entity;
     5     using System.Data.Entity.Infrastructure;
     6     
     7     public partial class remotingEntities : DbContext
     8     {
     9         public remotingEntities()
    10             : base("name=remotingEntities")
    11         {
    12         }
    13     
    14         protected override void OnModelCreating(DbModelBuilder modelBuilder)
    15         {
    16             throw new UnintentionalCodeFirstException();
    17         }
    18     
    19         public DbSet<user> users { get; set; }
    20     }
    21 }
    View Code

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

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

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

    简单的增删改查功能

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace EFConsole
     8 {
     9     class Program
    10     {
    11         public static remotingEntities dbContext = new remotingEntities();
    12         static void Main(string[] args)
    13         {
    14 
    15             add();
    16             select();
    17             update();
    18             remove();
    19             Console.ReadKey();
    20         }
    21 
    22 
    23         #region 添加方法
    24         /// <summary>
    25         /// 添加方法
    26         /// </summary>
    27         public static void add()
    28         {
    29             int res = -1;
    30             user tempData = new user() { name = "test", id = "1", balance = 1 };
    31             dbContext.users.Add(tempData);
    32             res = dbContext.SaveChanges();
    33             if (res > 0)
    34             {
    35                 Console.WriteLine("add function:suc");
    36             }
    37             else
    38             {
    39                 Console.WriteLine("add function:fail");
    40             }
    41         } 
    42         #endregion
    43 
    44         #region 查询方法
    45         /// <summary>
    46         /// 查询方法
    47         /// </summary>
    48         public static void select()
    49         {
    50             user tempData = dbContext.users.Where(e => e.id == "1").FirstOrDefault();
    51             Console.WriteLine("select function:" + tempData.name);
    52         } 
    53         #endregion
    54 
    55         #region 修改方法
    56         /// <summary>
    57         /// 修改方法
    58         /// </summary>
    59         public static void update()
    60         {
    61             int res = -1;
    62             user tempData = dbContext.users.Where(e => e.id == "1").FirstOrDefault();
    63             Console.WriteLine("before update function:" + tempData.name);
    64             tempData.name = "update name";
    65             res = dbContext.SaveChanges();
    66             if (res > 0)
    67             {
    68                 Console.WriteLine("update function:suc,update data userName is" + tempData.name);
    69             }
    70             else
    71             {
    72                 Console.WriteLine("update function :fail");
    73             }
    74         } 
    75         #endregion
    76 
    77         #region 删除方法
    78         /// <summary>
    79         /// 删除方法
    80         /// </summary>
    81         public static void remove()
    82         {
    83             int res = -1;
    84             user tempData = dbContext.users.Where(e => e.id == "1").FirstOrDefault();
    85             dbContext.users.Attach(tempData);
    86             dbContext.users.Remove(tempData);
    87             res = dbContext.SaveChanges();
    88             if (res > 0)
    89             {
    90                 Console.WriteLine("remove function :suc");
    91             }
    92             else
    93             {
    94                 Console.WriteLine("remove function :fail");
    95             }
    96         } 
    97         #endregion
    98     }
    99 }
    View Code

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

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

    项目源码

  • 相关阅读:
    正则表达式随笔
    linux 命令大全
    oracle merge into
    存储过程else if
    存储过程 loop
    存储过程 函数
    存储过程使用集合来存储查询
    存储过程使用游标和索引
    存储过程使用%rowtype定义游标类型的变量提取emp数据
    ORACLE 存储过程 like 样例
  • 原文地址:https://www.cnblogs.com/ljs0322/p/3787664.html
Copyright © 2011-2022 走看看