---
title: "支持不同Entity的DomainCollectionView模版"
author: "longyw"
date: "2014-03-08T12:51:09Z"
tags: ["Linq", "Silverlight"]
categories: ["编程语言"]
slug: "entity-domaincollectionview"
draft: false
lastmod: "2014-03-08T12:52:55Z"
id: 2028237
url: "https://longyw.iteye.com/blog/2028237"
---

用于Silverlight使用RiaService获取服务器端分页数据 using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Windows.Input; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.ComponentModel; using System.ServiceModel.DomainServices.Client; using System.ServiceModel.DomainServices; using Microsoft.Windows.Data.DomainServices; using ZL.Push.Web; namespace ZL.Push.Web { public sealed partial class ZLPushContext : DomainContext { public EntityQuery GetQuery(ref string entityName) where TEntity : Entity { this.ValidateMethod("Get" + entityName + "Query", null); return base.CreateQuery("Get" + entityName, null, false, true); } } } namespace ZL.Push { public class ZLViewModel : INotifyPropertyChanged where TEntity : Entity { #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler(this, e); } } protected void RaisePropertyChanged(string propertyName) { this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } #endregion private readonly ZLPushContext \_context = null; private readonly DomainCollectionView \_view; private readonly DomainCollectionViewLoader \_loader; private readonly EntityList \_source; public EntityList source { get { return \_source; } } private bool \_canLoad = false; private bool \_refresh\_current = false; private string \_searchText = string.Empty; private string \_entityName = string.Empty; #region View Properties public Expression&gt; lambda { get; set; } public bool CanLoad { get { return this.\_canLoad; } set { if (this.\_canLoad != value) { this.\_canLoad = value; this.RaisePropertyChanged("CanLoad"); } } } public ICollectionView CollectionView { get { return this.\_view; } } #endregion public ZLViewModel(ZLPushContext context, string entityName, bool refresh\_current = true) { lambda = null; \_context = context; \_entityName = entityName.Substring(0, 1).ToUpper() + entityName.Substring(1); \_refresh\_current = refresh\_current; this.\_source = new EntityList(this.\_context.EntityContainer.GetEntitySet()); this.\_loader = new DomainCollectionViewLoader( this.LoadEntities, this.OnLoadEntitiesCompleted); this.\_view = new DomainCollectionView(this.\_loader, this.\_source); INotifyCollectionChanged notifyingSortDescriptions =(INotifyCollectionChanged)this.CollectionView.SortDescriptions; notifyingSortDescriptions.CollectionChanged += (sender, e) =&gt; this.\_view.MoveToFirstPage(); } public void OnSearch() { // This makes sure we refresh even if we're already on the first page using (this.\_view.DeferRefresh()) { // This will lead us to re-query for the total count this.\_view.SetTotalItemCount(-1); this.\_view.MoveToFirstPage(); } } public void Clear() { this.\_source.Source = null; } public void AddNoSubmit(ref TEntity tbl) { this.\_source.Add(tbl); } public void Add(TEntity tbl, Action callback = null) { this.\_source.Add(tbl); this.\_context.SubmitChanges((op) =&gt; { if (op.HasError) { //恢复 this.\_source.Remove(tbl); op.MarkErrorAsHandled(); System.Windows.MessageBox.Show(op.Error.Message); } if (callback != null) { callback(!op.HasError); } }, false); } public void Edit(Action callback = null) { this.\_context.SubmitChanges((op) =&gt; { if (op.HasError) { op.MarkErrorAsHandled(); System.Windows.MessageBox.Show(op.Error.Message); } if (callback != null) { callback(!op.HasError); } }, false); } public void DeleteNoSubmit(TEntity tbl) { this.\_source.Remove(tbl); } public void Delete(TEntity tbl, Action callback = null) { int index = this.\_source.IndexOf(tbl); this.\_source.RemoveAt(index); this.\_context.SubmitChanges((op) =&gt; { if (op.HasError) { // 恢复 this.\_source.Insert(index, tbl); op.MarkErrorAsHandled(); System.Windows.MessageBox.Show(op.Error.Message); } if (callback != null) { callback(!op.HasError); } }, false); } private LoadOperation LoadEntities() { this.CanLoad = false; EntityQuery query = this.\_context.GetQuery(ref \_entityName); if (lambda != null) { query = query.Where(lambda); } // 如果不order by id，下面的SortAndPageBy会报错 var param = Expression.Parameter(typeof(TEntity), "c"); var body = Expression.PropertyOrField(param, "id"); var sortExpression = Expression.Lambda&gt;(body, param); query = query.OrderBy(sortExpression); if (\_refresh\_current) { return this.\_context.Load(query.SortAndPageBy(this.\_view), LoadBehavior.RefreshCurrent, false); } else { return this.\_context.Load(query.SortAndPageBy(this.\_view)); } } private void OnLoadEntitiesCompleted(LoadOperation op) { this.CanLoad = true; if (op.HasError) { op.MarkErrorAsHandled(); System.Windows.MessageBox.Show(op.Error.Message); } else if (!op.IsCanceled) { this.\_source.Source = op.Entities; if (op.TotalEntityCount != -1) { this.\_view.SetTotalItemCount(op.TotalEntityCount); } } } } } 使用示例代码： a) 绑定到datagrid并检索 ZLPushContext \_context = new ZLPushContext(); ZLViewModel \_vm = new ZLViewModel(\_context, "tbl\_metadata"); \_datagrid.DataContext = \_vm; \_datapager.DataContext = \_vm; \_vm.lambda = \_create\_lamda(); \_vm.OnSearch(); b) 添加entity tbl\_metadata tbl = new tbl\_metadata(); \_vm.Add(tbl, (result) =&gt; { if (result) { } } );