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.

  • 相关阅读:
    Luogu 1080 【NOIP2012】国王游戏 (贪心,高精度)
    Luogu 1314 【NOIP2011】聪明的质检员 (二分)
    Luogu 1315 【NOIP2011】观光公交 (贪心)
    Luogu 1312 【NOIP2011】玛雅游戏 (搜索)
    Luogu 1525 【NOIP2010】关押罪犯 (贪心,并查集)
    Luogu 1514 引水入城 (搜索,动态规划)
    UVA 1394 And Then There Was One / Gym 101415A And Then There Was One / UVAlive 3882 And Then There Was One / POJ 3517 And Then There Was One / Aizu 1275 And Then There Was One (动态规划,思维题)
    Luogu 1437 [HNOI2004]敲砖块 (动态规划)
    Luogu 1941 【NOIP2014】飞扬的小鸟 (动态规划)
    HDU 1176 免费馅饼 (动态规划)
  • 原文地址:https://www.cnblogs.com/kid1412/p/5493971.html
Copyright © 2011-2022 走看看