.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就會綁定這個資料來源了。
運行看看結果: