如何:使用反射提供程序创建数据服务(WCF 数据服务)

使用反射提供程序创建数据服务

使用 WCF 数据服务 可以定义基于任意类的数据模型,前提是这些类作为实现 IQueryable 接口的对象公开。

1、定义实例类(Post.cs)

using System.Data.Services.Common;

[DataServiceKeyAttribute("Id")]
public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

2、在实现 Bolg类中实现IQueryable 接口的对象公开

public class Bolg
{
    List<Post> post = new List<Post>();

    public Bolg()
    {
        post.Add(new Post { Id = 1, Title = "一步一步学Silverlight 2系列(13):数据与通信之WebRequest", Author = "TerryLee" });
        post.Add(new Post { Id = 2, Title = "一步一步学Silverlight 2系列(12):数据与通信之WebClient", Author = "TerryLee" });
        post.Add(new Post { Id = 3, Title = "一步一步学Silverlight 2系列(11):数据绑定", Author = "TerryLee" });
        post.Add(new Post { Id = 4, Title = "一步一步学Silverlight 2系列(10):使用用户控件", Author = "TerryLee" });
        post.Add(new Post { Id = 5, Title = "一步一步学Silverlight 2系列(9):使用控件模板", Author = "TerryLee" });
        post.Add(new Post { Id = 6, Title = "一步一步学Silverlight 2系列(8):使用样式封装控件观感", Author = "TerryLee" });
    }

    public IQueryable<Post> Posts
    {
        get { return post.AsQueryable<Post>(); }
    }

3、在同一命名空间下,创建WCF数据服务(BlogDataService.svc)

public class BlogDataService : DataService<Bolg>
{
    public static void InitializeService(IDataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("Posts", EntitySetRights.All);
    }
}

4、此时,即可在浏览器中浏览WCF数据服务了。

参考文件地址:http://msdn.microsoft.com/zh-cn/library/dd728281.aspx

原文地址:https://www.cnblogs.com/lanchong/p/2220294.html