原文链接:http://www.cnblogs.com/hjzhang/archive/2011/05/18/2050530.html
POCOs 是在Visual Studio 2010和ASP.NET 4.0中开始支持的一个新特性,其入门十分简单,下面我们基于Entity Framework 4.0.来实现一个基于POCOs的代码示例。
首先,创建一个测试工程
然后,新建一个Ado.NET Entity Data Model文件
如下图所示,定义两个类:Albums 和Photos
接下来我们还要确认是否已经关闭了代码自动生成,在Solution Explorer 选择edmx定义文件,在属性框确认Custom Tool为空,如下图所示:
定义以上两个对象的结构
- public class Albums
- {
- public Int32 Id { get; set; }
- public String AlbumName { get; set; }
- public String Remark { get; set; }
- public IList<Photos> Photos { get; set; }
- }
- public class Photos
- {
- public Int32 Id { get; set; }
- public String Name { get; set; }
- public String Description { get; set; }
- public String PicPath { get; set; }
- public Int32 Album_Id { get; set; }
- public Albums Albums { get; set; }
- }
然后建立自己的继承于ObjectContext的对象,在该对象中我们将定义需要使用LINQ查询的对象集合。如下所示:
- public class Mvc3SampleModel : ObjectContext
- {
- private readonly ObjectSet<Albums> _albums;
- private readonly ObjectSet<Photos> _photos;
- public Mvc3SampleModel()
- : base("Name=DbEntities", "DbEntities")
- {
- ContextOptions.LazyLoadingEnabled = true;
- _albums = CreateObjectSet<Albums>("Albums");
- _photos = CreateObjectSet<Photos>("Photos");
- }
- public ObjectSet<Albums> Albums
- {
- get { return _albums; }
- }
- public ObjectSet<Photos> Photos
- {
- get { return _photos; }
- }
下面演示基于LINQ进行查询的一般情况:
- public void GalleryTest()
- {
- var context = new Mvc3SampleModel();
- var visibleAlbums = from a in context.Albums
- where a.AlbumName !=null
- select a;
- foreach (var visibleAlbum in visibleAlbums)
- {
- Console.WriteLine(visibleAlbum.AlbumName);
- }
- var searchPhotos = from p in context.Photos
- where p.Name.StartsWith("M")
- select p;
- foreach (var searchPhoto in searchPhotos)
- {
- Console.WriteLine(searchPhoto.Name);
- }
- }
以下为测试结果
时间: 2024-10-13 00:54:51