您的位置:知识库 » .NET技术

一步一步学Silverlight :数据与通信之ADO.NET Data Services

作者: TerryLee  来源: 博客园  发布时间: 2008-10-09 11:53  阅读: 9167 次  推荐: 0   原文链接   [收藏]  

 

当然还可以进行其他的查询,使用filter和orderby等,如http://localhost:8081/BlogDataService.svc/Posts?$filter=Id eq 1&$orderby=Id,这里不在介绍。至此我们的数据服务端就算完成了。下面再实现客户端,XAML不再贴出来,大家可以参考前面的几篇文章,使用WebClient获取数据,返回的结果是一个XML文件:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    Uri uri = new Uri("http://localhost:8081/BlogDataService.svc/Posts");
    WebClient client = new WebClient();
    client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
    client.OpenReadAsync(uri);
}

void client_OpenReadCompleted(object sender,OpenReadCompletedEventArgs e)
{
    if (e.Error == null)
    {
        
    }
}

我们可以使用LINQ to XML进行数据的读取,在Silverlight项目中建立一个Post类,跟上面的Post类一样,然后使用LINQ to XML读取:

XmlReader reader = XmlReader.Create(e.Result);

XDocument postdoc = XDocument.Load(reader);

XNamespace xmlns = "http://www.w3.org/2005/Atom";
XNamespace ads = "http://schemas.microsoft.com/ado/2007/08/dataweb";

var posts = from x in postdoc.Descendants(xmlns + "entry")
            select new Post
            {
                Id = int.Parse(x.Descendants(ads + "Id").First().Value),
                Title = x.Descendants(ads + "Title").First().Value,
                Author = x.Descendants(ads + "Author").First().Value
            };

Posts.ItemsSource = posts;

完成的代码如下所示:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    Uri uri = new Uri("http://localhost:8081/BlogDataService.svc/Posts");
    WebClient client = new WebClient();
    client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
    client.OpenReadAsync(uri);
}

void client_OpenReadCompleted(object sender,OpenReadCompletedEventArgs e)
{
    if (e.Error == null)
    {
        XmlReader reader = XmlReader.Create(e.Result);

        XDocument postdoc = XDocument.Load(reader);

        XNamespace xmlns = "http://www.w3.org/2005/Atom";
        XNamespace ads = "http://schemas.microsoft.com/ado/2007/08/dataweb";

        var posts = from x in postdoc.Descendants(xmlns + "entry")
                    select new Post
                    {
                        Id = int.Parse(x.Descendants(ads + "Id").First().Value),
                        Title = x.Descendants(ads + "Title").First().Value,
                        Author = x.Descendants(ads + "Author").First().Value
                    };

        Posts.ItemsSource = posts;
    }
}

完整的示例就到这里了,运行后的结果与前面的一样。

TerryLee_Silverlight2_0065

结束语

本文简单介绍了在Silverlight 2调用ADO.NET Data Services,由于对ADO.NET Data Services了解不多,有错误的地方还请大家斧正,你可以从这里下载示例代码。

0
0
 

.NET技术热门文章

    .NET技术最新文章

      最新新闻

        热门新闻