使用Silverlight + DomainService进行开发时我们可以在Silverlight项目中创建一个BLL层用于Silverlight调用如下图所示
要完成数据查询功能在Sliverlight项目中做了这么几项工作
1.定义查询处理委托
public delegate void SelectHander<T>(IEnumerable<T> data);
2.编写BLL代码
我这里写了一个DB类用于处理DomainService对象,代码如下
public class DB { private static DomainService1 _db; public static DomainService1 db { get { if (_db == null) _db = new DomainService1(); return _db; } } }
2.1普通全查功能
public class RoleBLL { public static void FindAll(SelectHander<UserRoles> sh) { var db = DB.db; var m = db.Load<UserRoles>(db.GetUserRolesQuery()); m.Completed += (a, b) => { sh(m.Entities); }; } }
2.2如果要完成带条件查询需要在Web服务端进行处理
2.2.1 修改原来的
public class DomainService1 : LinqToEntitiesDomainService<MyBookShopEntities>
改为
public partial class DomainService1 : LinqToEntitiesDomainService<MyBookShopEntities>
这样自己就可以再写一个局部类来扩充DomainService1的代码
public partial class DomainService1 { public IQueryable<UserRoles> GetUserRolesByName(string name) { return this.ObjectContext.UserRoles.Where(r => r.Name.StartsWith(name)); } }
2.2.2这样在Silverlight端的RoleBLL就可以调用服务端的查询,Silverlight端代码如下:
public class RoleBLL { public static void FindAll(SelectHander<UserRoles> sh) { var db = DB.db; var m = db.Load<UserRoles>(db.GetUserRolesQuery()); m.Completed += (a, b) =>{sh(m.Entities);}; } public static void FindAllByName(string name, SelectHander<UserRoles> sh) { var db = DB.db; var m = db.Load<UserRoles>(db.GetUserRolesByNameQuery(name)); m.Completed += (a, b) => { sh(m.Entities); }; } }
3.Silverlight表示层端调用
public MainPage() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainPage_Loaded); } void MainPage_Loaded(object sender, RoutedEventArgs e) { RoleBLL.FindAll(datas => { userRolesDataGrid.ItemsSource = datas; }); }
效果:
条件查询代码:
private void btnQuery_Click(object sender, RoutedEventArgs e) { RoleBLL.FindAllByName(txtName.Text, datas => { userRolesDataGrid.ItemsSource = datas; }); }
效果: