.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 = "bb@hob.me"}, new Customer() { CustomerId = 2, FirstName="Frodo", LastName = "Baggins", EmailAddress = "fb@hob.me"}, new Customer() { CustomerId = 3, FirstName="Samwise", LastName = "Gamgee", EmailAddress = "sg@hob.me"}, new Customer() { CustomerId = 4, FirstName="Rosie", LastName = "Cotton", EmailAddress = "rc@hob.me"}}; return custList; } } }
为了简便没有做从数据库或则其他数据源获取数据,这里就直接模拟一些数据。
每个用户的CustomerId应该是唯一的,所以这里需要把CustomerId定义成为主键。引用下面的命名空间。
using System.ComponentModel.DataAnnotations;
然后在CustomerId属性加上特性Key。
[Key] public int CustomerId { get; set; }
6.在PocoSample.Web项目,新增一个DomainService,名字为CustomerDomainService.cs。
在弹出的Add New Domain Service Class窗口单击OK即可。
如果你使用EDMX文件的话,可以在Avaiable DataContext/ObjectContext classes下拉框中找到,在生成的Domain Service类是继承LinqToEntitiesDomainService的泛型类的,如果是自定义的Domain Service类的话,生成的类是继承DomainService的。
7.在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>
9.在DataSource面板,可以看到程序中的所有数据源,其中CustomerDomainContext是我们刚刚自定义的数据源。选择GetCustomersQuery方法,和DataGird。
拖动Customer到DataGrid的上面,然后松开鼠标。这样DataGrid就会绑定这个数据源了。
运行看看结果: