从零学习Entity Framework

       以前在学校的时候没有使用过 Entity Framework 框架,这段时间不怎么忙,就想把这个框架学习一下。其实我对这个也不是

很理解,就是把自己学习的过程记录下来,预防自己会忘记,我一直是一个记性不太好的人。好吧现在就开始了。

      1.环境VS2010+MS-SQL 你有其它版本的vs和数据库也行。其实我也不知道要.net Framework 那个版本才支持这个框架的。

3或3.5以上应该都没问题

      2.安装Nuget

        Tools->Extension magage->搜索Nuget
        注意:如果你查找到的Nuget 里面的按钮时灰色的,说明你安装了,点击update 如果可以点击你就更新Nuget,因为好像不是最新的Nuget

就没法安装 Entity Framework 安装好了之后,重启下VS。

      3.安装Entity Framework

       Tools->Nuget package manager->package manager console 在控制台输入 Install-Package EntityFramework 

一般情况下这样做事会报错。原因是因为你没有建立一个项目。所以我在这就先建立一个控制台项目(EFTest)重复三步骤就安装

好了,仔细看你会发现你的项目里会多两个文件(packages.config,App.config),同时也帮我们引进了一些需要的dll.

      4.配置连接数据库

         打开App.config文件,添加如下节点 

<connectionStrings>
   <add name="DbHelper" providerName="System.Data.SqlClient" connectionString="Server=(local);Database=EFTest;Trusted_Connection=true;"/>
</connectionStrings>

  说明下:name :属性一般为你操作数据库的那么类的类名。

                 Databass: 就是你需要框架帮你建的数据库(不需要先去数据库建立)

      添加的位置为:

<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=4.3.1.0, Culture=neutral, PublicKey     Token=b77a5c561934e089" />
  </configSections>

之后。
<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=4.3.1.0, Culture=neutral, PublicKey     Token=b77a5c561934e089" />
  </configSections>
<connectionStrings>
   <add name="DbHelper" providerName="System.Data.SqlClient" connectionString="Server=(local);Database=EFTest;Trusted_Connection=true;"/>
</connectionStrings>

  5.下面上一个简单的例子

         Model:也就是两个实体类

  file: Category.cs   

   class Category
    {
        public int ID{get;set;}
        [Required]
        public string catename { get; set; }
    }

 

 class Commodity
    {
        public int ID { get; set; }
        [Required]
        public string name{get;set;}
        public float oneprice { get; set; }
        [Required]
        public virtual Category cate { get; set; }

    }

  

  说明:当需要这类[Required]标签时 需要引进命名空间  using System.ComponentModel.DataAnnotations;

     改命名空间还好包含的标签有

      [key]   定义主键数据库主键  由于coding-first 采用的是约定大于配置。这里有个疑问 当model里有ID,又有[Key]标识的其它属性时,EF

    是让谁做主键,这个我没有在编辑器里试试。改天试下。

      [MaxLenth(xxx)]    数据库字段长度 

      [MinLenth(xxx)]     数据库字段长度

      [Required]            必填写的

      [NotMapped]  不与数据库匹配的字段,也就意味着不会再数据库里创建该字段

      混合使用

      [MaxLenth(20),MinLenth(6)]

      其他的用法可以 查找一下命名空间 DataAnnotations

      重要:我使用的是EF6.1 我发现不加 virtual 也可以建立外键关联。

    file:Dbhelper.cs

    class DbHelper : DbContext
    {
    
        public DbSet<Category> Category { get; set; }
        public DbSet<Commodity> Commodity { get; set; }

    }

  说明:这里需要引进命名空间 using System.Data.Entity;

      这样就可以操作数据库了。

下面是对数据库的基本操作了;

        给  Category 表添加数据

            DbHelper context = new DbHelper();
            Console.WriteLine("请输入商品类别:");
            string udname = Console.ReadLine();
            Category ug = new Category();
            ug.catename = udname;
            context.Category.Add(ug);
            context.SaveChanges();
            Console.WriteLine("添加成功");

  给   Category 表修改数据 (我用的是一种比较笨的方法,我觉得实际开发应该不会用方法来修改数据)

               var gr = context.Category.Select(a => a).ToList();//获取Category表的所有数据
                gr.ForEach(b => Console.WriteLine("{0:######}   {1:######}", b.ID, b.catename));//遍历表的数据
                /*   另外一种遍历方式          
                        Category ag=new Category(); 
                        for(int i=0;i<gr.Count;i++){
                          ag=gr.ElementAt(i)
                         }
                */
                Console.WriteLine("请选择要修改的商品类别:");
                int grid = int.Parse(Console.ReadLine().Trim());
                if (grid > 0)
                {
                    Category gro = context.Category.Where(t => t.ID == grid).SingleOrDefault();
                    Category aa = new Category();
                    Console.WriteLine("请输入修改后的名字:");
                    aa.catename = Console.ReadLine().Trim();
                    context.Category.Remove(gro);
                    context.Category.Add(aa);
                    context.SaveChanges();
                    Console.WriteLine("修改成功");

                }
                else
                {
                    Console.WriteLine("您输入的不是类别,请从输");
                   
                }

  

     给  Category 表查询所有数据  

                var gr = context.Category.Select(a => a).ToList();
                gr.ForEach(b => Console.WriteLine("{0:######} {1:######}", b.ID, b.catename));

  说明:如果查询一定条件的数据可以用这种形式 var apu = context.Category.Where(a => a.ID > 3).ToList();

     给 Category 表删除数据 

               var gr = context.Category.Select(a => a).ToList();
                gr.ForEach(b => Console.WriteLine("{0:######}   {1:######}", b.ID, b.catename));
                Console.WriteLine("请选择要删除的分组:");
                int grid = int.Parse(Console.ReadLine().Trim());
                if (grid > 0)
                {
                    Category gro = context.Category.Where(t => t.ID == grid).SingleOrDefault();
                    context.Category.Remove(gro);
                    context.SaveChanges();
                    Console.WriteLine("删除成功");
                }
                else
                {
                    Console.WriteLine("您输入的不是分组,请从输");
                                 
}

  这是单独一张表的操作,假如需要查询Commodity 表,该表有导航属性时,就需要用下面的方法

            DbHelper context = new DbHelper();
            var alluser = context.Commodity.Include(a => a.cate).ToList();
            alluser.ForEach(a =>
             Console.WriteLine("{0:######}   {1:################}    {2:############}  {3:########} ",a.ID.ToString(),a.name,a.cate.catename,a.oneprice.ToString()));
            context.Dispose();

  

    如果代码里有调用 context.SaveChanges();就不需要 调用context.Dispose()显示的释放。

   我在学习的时候遇到一个问题就是,不知道怎样实现这种SQL语句 :select *  from table where table.ID in (1,2,3,4) 这类的写法,找了下没资料

  没有找到,知道的希望告诉下我!547304838@qq.com,需要代码的也可以发邮件到这个邮箱,我会一一发!

         今天学习的就到这了,记录下,以便自己跟快回忆起来!

              

     

原文地址:https://www.cnblogs.com/try-wyh/p/3689365.html