@Tariq Salah
hi,Tarip,this post is reprinted from
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2007/10/09/9848.aspx
"原文:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2007/10/09/9848.aspx"
"原文" == original post:)
"LINQ to SQL and WCF - Sharing types, subverting the DataContext on the client side(转)"
"转" == Reprint:)
for your question:
public class EntityBindingList<TEntity> : BindingList<TEntity> where TEntity : class
{
private ClientSideContext context;
public ClientSideContext Context
{
get { return context; }
}
public EntityBindingList(IList<TEntity> entities)
: base(entities)
{
context = new ClientSideContext();
context.AttachAll<TEntity>(entities);
}
protected override void InsertItem(int index, TEntity item)
{
base.InsertItem(index, item);
Context.Add<TEntity>(item);
}
protected override void RemoveItem(int index)
{
Context.Remove<TEntity>(this[index]);
base.RemoveItem(index);
}
}
public class ClientSideContext
{
private DataContext ctx;
public class StateEntries<T>
{
public List<T> Originals { get; set; }
public List<T> Current { get; set; }
}
public ClientSideContext()
{
ctx = new DataContext("", new AttributeMappingSource());
ctx.DeferredLoadingEnabled = false;
}
public void Attach<T>(T t) where T : class
{
ctx.GetTable<T>().Attach(t);
}
public void AttachAll<T>(IEnumerable<T> entities) where T : class
{
ctx.GetTable<T>().AttachAll(entities);
}
public void Remove<T>(T t) where T : class
{
ctx.GetTable<T>().DeleteOnSubmit(t);
}
public void Add<T>(T t) where T : class
{
ctx.GetTable<T>().InsertOnSubmit(t);
}
public List<T> GetInserted<T>() where T : class
{
return (GetChangeEntries<T>(ch => ch.Inserts));
}
public StateEntries<T> GetDeleted<T>() where T : class
{
return (GetStateEntries<T>(ch => ch.Deletes));
}
private StateEntries<T> GetStateEntries<T>(
Func<ChangeSet, IEnumerable<Object>> entry) where T : class
{
List<T> current = GetChangeEntries<T>(entry);
List<T> originals = GetOriginals<T>(current);
return (new StateEntries<T>()
{
Originals = originals,
Current = current
});
}
public StateEntries<T> GetModified<T>() where T : class
{
return (GetStateEntries<T>(ch => ch.Updates));
}
List<T> GetChangeEntries<T>(
Func<ChangeSet, IEnumerable<Object>> selectMember) where T : class
{
var query = from o in selectMember(ctx.GetChangeSet())
where ((o as T) != null)
select (T)o;
return (new List<T>(query));
}
List<T> GetOriginals<T>(List<T> current) where T : class
{
List<T> originals = new List<T>(
from c in current
select ctx.GetTable<T>().GetOriginalEntityState(c));
return (originals);
}
public void Dispose()
{
ctx.Dispose();
}
}