EF之POCO应用系列3——复杂类型

   在.NET开发中,EF4以前的版本以及LINQ TO SQL都不支持complex数据类型,EF4终于支持complex类型的数据了,这意味着微软的EF框架朝领域驱动方面又迈了一大步。

    复杂的数据类型其实就是一个POCO类,想想曾几何时,我们想在开发时想设计一个用户信息类,我们写的类不得不包括以下信息:

public class UserInfo{

     public int UID{GET;SET};

     public string Identity{get;set};

     public string FirstName{get;set};

     public string LastName{get;set};

}

我们的姓名一般都是包括FirstName和LastName组成。我们现在改成复杂的数据类型看看是如何实现的

public class UserInfo{

     public int UID{GET;SET;};

     public string Identity{get;set};

     public Name name{get;set;};

}

public class Name{

     public string FirstName{get;set};

     public string LastName{get;set};

}

还是继续接上一篇中的Northwind,我们继续扩展product类,为该类添加一个复杂类型库存详细资料“InventoryDetail”。

1、打开“Northwind.edmx”,点击product-》添加-》复杂类型。

2、打开模型浏览器,为复杂类型添加标量属性,如下图:

image

为详细资料类添加如下属性:

    public Int16 UnitsInStock { get; set; }
    public Int16 UnitsOnOrder { get; set; }
    public Int16 ReorderLevel { get; set; }
3、在工程NorthwindModel中添加InventoryDetail.cs文件,代码如下;

View Code
1 public class InventoryDetail
2 {
3 public Int16 UnitsInStock { get; set; }
4 public Int16 UnitsOnOrder { get; set; }
5 public Int16 ReorderLevel { get; set; }
6 }

4、更改product.cs代码,增加复杂类型“InventoryDetail”如下:

View Code
1 public class Product
2 {
3 public int ProductID { get; set; }
4 public string ProductName { get; set; }
5 public int SupplierID { get; set; }
6 public string QuantityPerUnit { get; set; }
7 public decimal UnitPrice { get; set; }
8 public InventoryDetail InventoryDetail { get; set; }
9 public bool Discontinued { get; set; }
10 public Category Category { get; set; }
11 }

注意红色的部分。

现在可以在测试中用如下代码进行查找库存详细资料了:

var outOfStockProducts = from c in context.Products
                         where c.InventoryDetail.UnitsInStock == 0
                         select c;

posted @ 2011-05-11 09:46  sunrfun  阅读(3779)  评论(0编辑  收藏  举报