Entity Framework 简单查询

前言

首先来简单的复习一下如何使用Code First。

第一步还是先建立一个控制台的应用程序,然后通过Nuget添加Entity Framework。那么同时会给packages.config和App.config添加相应的配置。

第二步添加一个数据操作上下文实体类。添加两个构造函数,并添加一个Person的实体类。 在App.config的配置文件中添加相应的数据链接配置。

第三步在调用即可生成相应的数据库。

 EFContext.cs

    public class EFContext:DbContext
    {
        public EFContext()
            : base("EFContext")
        { }

        public EFContext(string connectionstring)
            :base(connectionstring)
        {
               
        }

        public DbSet<Person> Persons { get; set; }
    }

  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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="EFContext" connectionString="Data Source=.;Database=EFContext;UID=sa;PWD=sa123;" providerName="System.Data.SqlClient"></add>
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

 package.config 

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="5.0.0" targetFramework="net45" />
</packages>

  然后简单的添加了一个实体类

    public class Person
    {
        public int PersonId { get; set; }

        public string PersonName { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        public string Email { get; set; }
    }

  最终进行调用

        static void Main(string[] args)
        {
            using (var db = new EFContext("EFContext"))
            {
                var persons = db.Persons.Where(t => t.PersonName == "aehyok").OrderByDescending(t => t.PersonId).ToList();
                foreach (var p in persons)
                {
                    Console.WriteLine("The PersonName is {0} and Age {1}", p.PersonName, p.Age);
                }
            }
            Console.ReadLine();
        }

  运行后控制台没有数据显示,但是在数据库里可以查看到相应的数据库EFContext和数据表People。

 现在我们通过数据库直接为上面建立的数据库EFContext中的People表手动添加了几条数据。

 

然后重新运行程序。可以发现有数据了。

此时可以发现我们的第一个简答的查询语句已经实现了。

  一个数据库上下文的生命周期随着该对象的创建而开始,随着对象的释放(或GC回收)而结束,因此建议在开发过程中使用“Using”编码方式,这样就可以免去手动释放对象的操作。另外对于数据库连接的管理在EF中是透明的,我们一般不需要手动进行处理,当查询一个对象时打开连接当处理完查询的结果集之后会自动关闭连接。

Linq To Entity表达式查询

 查询表达式是C#3.0新增的功能,它是由一组类似于T-SQL或XQuery声明性语句组成,CLR并不能直接读取这种查询表达式而是在编译时转换为对应的方法调用。如下面的例子:

            using (var db = new EFContext("EFContext"))
            {
                var persons = from p in db.Persons
                              where p.PersonName == "aehyok"
                              orderby p.PersonId descending
                              select p;
                foreach (var p in persons)
                {
                    Console.WriteLine("The PersonName is {0} and Age {1}", p.PersonName, p.Age);
                }
            }
            Console.ReadLine();

  得到的结果同上面是一致的。

基于方法的查询

基于方法的查询事实上是一组对象的扩展方法,同Linq查询不同的是这些方法可以直接被CLR识别并运行。

例如上面的方法我们可以转换为如下代码,他们的效果是一样的,返回的都是“IQueryable”对象,这里的代码其实也就是我们开始为创建数据库测试的代码

            using (var db = new EFContext("EFContext"))
            {
                var persons = db.Persons.Where(t => t.PersonName == "aehyok").OrderByDescending(t => t.PersonId).ToList();
                foreach (var p in persons)
                {
                    Console.WriteLine("The PersonName is {0} and Age {1}", p.PersonName, p.Age);
                }
            }
            Console.ReadLine();

  当然执行的结果还是一样的。

原生SQL的查询

EF还支持原生SQL查询例如:

            using (var db = new EFContext("EFContext"))
            {
                var persons = db.Persons.SqlQuery("select * from EFContext..People where PersonName='aehyok'");
                foreach (var p in persons)
                {
                    Console.WriteLine("The PersonName is {0} and Age {1}", p.PersonName, p.Age);
                }
            }
            Console.ReadLine();

  可以直接通过SQL语句的拼接额,当然这里只是做了最简单的实例。

  不仅如此,EF还支持非实体类型的查询:

            using (var db = new EFContext("EFContext"))
            {
                var persons = db.Database.SqlQuery<string>("select PersonName from EFContext..People where PersonName='aehyok'");
                foreach (var p in persons)
                {
                    Console.WriteLine("The PersonName is {0} ", p);
                }
            }

 

当然也支持无返回值的SQL命令:

            using (var db = new EFContext("EFContext"))
            {
                var persons = db.Database.ExecuteSqlCommand("update EFContext..People set Address='中国' where PersonName='aehyok'");
            }

  

posted @ 2013-09-30 09:04  aehyok  阅读(5069)  评论(2编辑  收藏  举报