zoukankan      html  css  js  c++  java
  • Entity Framework 6 Recipes 2nd Edition(13-2)译 -> 用实体键获取一个单独的实体

    问题

    不管你用DBFirst,ModelFirst或是CodeFirst的方式,你想用实体键获取一个单独的实体.在本例中,我们用CodeFirst的方式.

    解决方案

    假设你有一个模型表示一个Painting(绘画)类型的实体,如Figure 13-2所示:

    Figure 13-2. The Painting entity type in our model

    在代码In Listing 13-2,我们创建实体类Painting.

      public class Painting

        {

            public string AccessionNumber { get; set; }

            public string Name { get; set; }

            public string Artist { get; set; }

            public decimal LastSalePrice { get; set; }

    }

    接下来,在代码Listing 13-3,我们创建DbContext对象(我们用CodeFirst方式时,EF的门户)

    Listing 13-3. DbContext Object

      public class Recipe2Context : DbContext

        {

            public Recipe2Context()

                : base("Recipe2ConnectionString")

            {

                // Disable Entity Framework Model Compatibility

                Database.SetInitializer<Recipe2Context>(null);

            }

            protected override void OnModelCreating(DbModelBuilder modelBuilder)

            {

                // map AccessionNumber as primary key to table

                modelBuilder.Entity<Painting>().HasKey(x => x.AccessionNumber);

                modelBuilder.Entity<Painting>().ToTable("Chapter13.Painting");

            }

            public DbSet<Painting> Paintings { get; set; }

    }

    接下来在项目里添加App.config,并把Listing 13-4代码添加到ConnectionStrings节下,

    Listing 13-4. Connection String

    <connectionStrings>

    <add name="Recipe2ConnectionString"

    connectionString="Data Source=.;

    Initial Catalog=EFRecipes;

    Integrated Security=True;

    MultipleActiveResultSets=True"

    providerName="System.Data.SqlClient" />

    </connectionStrings>

    在代码Listing 13-5,我们装载数据,演示两种获取实体的方法:LinQ查询和Find()方法.

    Listing 13-5. Retrieving an Entity with the Find() Method

       private static void RunExample()

            {

                using (var context = new Recipe2Context())

                {

                    context.Paintings.Add(new Painting

                    {

                        AccessionNumber = "PN001",

                        Name = "Sunflowers",

                        Artist = "Rosemary Golden",

                        LastSalePrice = 1250M

                    });

                }

                using (var context = new Recipe2Context())

                {

                    // LINQ 查询总是会从数据库获取实体,即使实体已经存在于上下文中

                    var paintingFromDatabase =

                    context.Paintings.FirstOrDefault(x => x.AccessionNumber == "PN001");

     

                    // Find() 方法会从上下文中获取实体,如果不存在再从数据库获取

                    var paintingFromContext = context.Paintings.Find("PN001");

                }

                Console.WriteLine("Press <enter> to continue...");

                Console.ReadLine();

            }

    它是如何工作的

    当用LinQ查询时,它都会从数据库中获取所需的数据,即使这些数据已经被装载进了内存中的上下文(Context)对象里,当这个查询结束,如果实体尚不存在于上下文,那么则会被加入上下文,并且被跟踪.默认情况下,如果实体对象已经存在于上下文,它不会被从数据库新获取的数据重写.

             然而,封装了实体对象的DbSet对象,暴露一个Find()方法,该方法需要提供一个主键参数.如组合主键,就需要给它传递一个数组.Find()方法是非常有效率的,它先会在上下文中查找目标对象,如果找到,它就直接从上下文中返回,如果找不到,它自动查询数据库,如果还是找不到,就返回null.另外,Find()方法可以返回一个已经被添加(状态为Added)但未保存到数据库的实体.而且Find()方法可以在三种方式中使用:DBFirst,ModelFirst,CodeFirst.

             在Listing 13-5,我们先调用LinQ查询来获取一个Painting.图 Figure 13-3显示了产生的SQL查询

    Figure 13-3. SQL Query returning our painting

    接着的下行代码,我们用Find()方法来获取相同的实体,我们给它传递了一个主键参数(“PN001”),它首先在上下文对象中查找主键为PN001的实体,找到之后,返回该实体的一个引用,避免了对数据库查询.如图Figure 13-4所示,数据库中并没有SQL语句产生

    Figure 13-4. The Find() method locates the object in memory, not generating a database query

             查看 Find()方法的更多信息,请查看 Recipe 5-3.

  • 相关阅读:
    Python之路第十二天,高级(5)-Python操作Mysql,SqlAlchemy
    Python之路第十二天,高级(4)-Python操作rabbitMQ
    Python之路第十一天,高级(3)-线程池
    day11 消息队列、多线程、多进程、协程
    day10 多进程、多线程(一)
    day09编程之socket
    day08面向对象(二)
    day07面向对象(初级篇)
    day06反射和正则
    day05开发 (字符串格式化和常用模块)
  • 原文地址:https://www.cnblogs.com/kid1412/p/5493971.html
Copyright © 2011-2022 走看看