首先介绍一个比较好的入门资料:Taking a Tour of RIA Services, 可以先看下这个,本文可以看做一点儿小小的补充
http://msdn.microsoft.com/en-us/library/ff713719(v=VS.91).aspx
github代码地址:git@github.com:kiwiwin/silverlight-demo.git 。文件夹:ria-association-domain-service。因为跟数据库相关,可能直接跑不起来。
现在有两个表,分别是Book和Record,Record中含有一个外键bookId,只想Book的Id。我们希望在客户端得到一个借阅记录的表。
添加ADO.NET ENTITY Data Model: LibraryModel.edmx
添加Domain Service Class:LibraryService.cs(注意,在这之前需要先build .Web,不然不会找到上一步生成的Model)
选上Book和Record两个Table
在LibraryService.metadata.cs中有两个Table对应的数据结构的定义,找到Record:(可以好好看看里面自动生成的注释)
// The MetadataTypeAttribute identifies RecordMetadata as the class // that carries additional metadata for the Record class. [MetadataTypeAttribute(typeof(Record.RecordMetadata))] public partial class Record { // This class allows you to attach custom attributes to properties // of the Record class. // // For example, the following marks the Xyz property as a // required property and specifies the format for valid values: // [Required] // [RegularExpression("[A-Z][A-Za-z0-9]*")] // [StringLength(32)] // public string Xyz { get; set; } internal sealed class RecordMetadata { // Metadata classes are not meant to be instantiated. private RecordMetadata() { } public Book Book { get; set; } public int bookId { get; set; } public DateTime endTime { get; set; } public int id { get; set; } public DateTime startTime { get; set; } } }
这里虽然有Book,但是在LibraryService.cs中的 public IQueryable<Record> GetRecords()方法中,是不会返回Book对象的,如果需要,则需要在Book上加上Attribute Include
[Include] public Book Book { get; set; }
然后修改public IQueryable<Record> GetRecords(),加上Include("Book")这样返回的对象才会包括Book
public IQueryable<Record> GetRecords() { return this.ObjectContext.Records.Include("Book"); }
这样就能从服务器端返回所有的Record和它对应的Book啦
在客户端显示,定义DomainDataSource和一个DataGrid
<riaControls:DomainDataSource Name="libraryDataSource" LoadSize="20" AutoLoad="True" QueryName="GetRecords"> <riaControls:DomainDataSource.DomainContext> <ds:LibraryContext/> </riaControls:DomainDataSource.DomainContext> </riaControls:DomainDataSource> <sdk:DataGrid AutoGenerateColumns="False" Width="600" Height="300" ItemsSource="{Binding Path=Data, ElementName=libraryDataSource}"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Binding="{Binding Book.Name}" Header="书名"/> <sdk:DataGridTextColumn Binding="{Binding Book.Isbn}" Header="ISBN"/> <sdk:DataGridTextColumn Binding="{Binding startTime}" Header="开始时间"/> <sdk:DataGridTextColumn Binding="{Binding endTime}" Header="结束时间"/> </sdk:DataGrid.Columns> </sdk:DataGrid>
运行吧骚年: