.net 4的Entity Framework4已经支持POCO(Plan Old CLR Object),我们可以不用事先生成EDMX文件,通过编写实体类的方式将实体对象独立。这里记录如何在Silverlight程序中使用POCO查询数据。
1.新建Silverlight Business Application模板的项目,名字为POCOSample。
2.在POCOSample项目的Views文件夹下新增一个Silvelight Page。名字为Customers.xaml。
3.在Grid标记内加入下面的XAML代码:
<StackPanel Margin="0,12,0,12" Orientation="Vertical" > <TextBlock Text="Customer List" Style="{StaticResource HeaderTextStyle}"/> </StackPanel>4.打开MainPage.xaml的文件,在链接Home和About之间加入下面的XAML代码:
<HyperlinkButton x:Name="Link3" Style="{StaticResource LinkStyle}" NavigateUri="/Customers" TargetName="ContentFrame" Content="Customer List"/> <Rectangle x:Name="Divider2" Style="{StaticResource DividerStyle}"/>5.在HRApp项目新增实体类Customer,代码如下:
public class Customer { /// <summary> /// Manages a customer /// </summary> public class Customer { public int CustomerId { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string EmailAddress { get; set; } /// <summary> /// Retrieves a list of customers. /// </summary> /// <returns></returns> /// <remarks> /// In a "real" application, this code would /// call a data access component that retrieves /// the data from a database. /// </remarks> public List<Customer> Retrieve() { List<Customer> custList = new List<Customer> {new Customer() { CustomerId = 1, FirstName="Bilbo", LastName = "Baggins", EmailAddress = "[email protected]"}, new Customer() { CustomerId = 2, FirstName="Frodo", LastName = "Baggins", EmailAddress = "[email protected]"}, new Customer() { CustomerId = 3, FirstName="Samwise", LastName = "Gamgee", EmailAddress = "[email protected]"}, new Customer() { CustomerId = 4, FirstName="Rosie", LastName = "Cotton", EmailAddress = "[email protected]"}}; return custList; } } }为了简便没有做从数据库或则其他数据源获取数据,这里就直接模拟一些数据。
using System.ComponentModel.DataAnnotations;
然后在CustomerId属性加上特性Key。
[Key] public int CustomerId { get; set; }6.在PocoSample.Web项目,新增一个DomainService,名字为CustomerDomainService.cs。
[EnableClientAccess()] public class CustomerDomainService : DomainService { public IEnumerable<Customer> GetCustomers() { Customer cust = new Customer(); return cust.Retrieve(); } }8.打开Customers.xaml,在CustomerList的TextBlock下面加入DataGrid。设置IsReadOnly为True,AutoGenerateColumns为True。
<StackPanel Margin="0,12,0,12" Orientation="Vertical" > <TextBlock Text="Customer List" Style="{StaticResource HeaderTextStyle}"/> <sdk:DataGrid AutoGenerateColumns="True" IsReadOnly="True" Height="156" Name="dataGrid1" Width="532" /> </StackPanel>