POCOs 是在Visual Studio 2010和ASP.NET 4.0中开始支持的一个新特性,其入门十分简单,下面我们基于Entity Framework 4.0.来实现一个基于POCOs的代码示例。

        首先,创建一个测试工程

        然后,新建一个Ado.NET Entity Data Model文件

image

       如下图所示,定义两个类:Albums 和Photos

image

      接下来我们还要确认是否已经关闭了代码自动生成,在Solution Explorer 选择edmx定义文件,在属性框确认Custom Tool为空,如下图所示:

image

定义以上两个对象的结构

  1. public class Albums
  2.     {
  3.         public Int32 Id { get; set; }
  4.         public String AlbumName { get; set; }
  5.         public String Remark { get; set; }
  6.         public IList<Photos> Photos { get; set; }
  7.     }
  1. public class Photos
  2.     {
  3.         public Int32 Id { get; set; }
  4.         public String Name { get; set; }
  5.         public String Description { get; set; }
  6.         public String PicPath { get; set; }
  7.         public Int32 Album_Id { get; set; }
  8.         public Albums Albums { get; set; }
  9.     }

然后建立自己的继承于ObjectContext的对象,在该对象中我们将定义需要使用LINQ查询的对象集合。如下所示:

  1. public class Mvc3SampleModel : ObjectContext
  2.     {
  3.         private readonly ObjectSet<Albums> _albums;
  4.         private readonly ObjectSet<Photos> _photos;
  5.  
  6.         public Mvc3SampleModel()
  7.             : base("Name=DbEntities", "DbEntities")
  8.         {
  9.             ContextOptions.LazyLoadingEnabled = true;
  10.             _albums = CreateObjectSet<Albums>("Albums");
  11.             _photos = CreateObjectSet<Photos>("Photos");
  12.         }
  13.  
  14.         public ObjectSet<Albums> Albums
  15.         {
  16.             get { return _albums; }
  17.         }
  18.  
  19.         public ObjectSet<Photos> Photos
  20.         {
  21.             get { return _photos; }
  22.         }

下面演示基于LINQ进行查询的一般情况:

  1. public void GalleryTest()
  2.       {
  3.           var context = new Mvc3SampleModel();
  4.           var visibleAlbums = from a in context.Albums
  5.                               where a.AlbumName !=null
  6.                               select a;
  7.           foreach (var visibleAlbum in visibleAlbums)
  8.           {
  9.               Console.WriteLine(visibleAlbum.AlbumName);
  10.           }
  11.           var searchPhotos = from p in context.Photos
  12.                              where p.Name.StartsWith("M")
  13.                              select p;
  14.           foreach (var searchPhoto in searchPhotos)
  15.           {
  16.               Console.WriteLine(searchPhoto.Name);
  17.           }
  18.       }

    以下为测试结果

image

 posted on 2011-05-18 22:26  James Cheung  阅读(1297)  评论(0编辑  收藏  举报