UnitOfWork をリポジトリ パターンと共に使用しています。アーキテクチャは、LINQ-to-SQL クラスをモデルとして直接使用する MVVM です。次のコード スニペットは、汎用リポジトリ、サンプル (都市リポジトリ)、および UnitOfWork クラスを示しています。
汎用リポジトリ:
public abstract class Repository<T> : IRepository<T> where T : class
{
protected Table<T> _objectSet;
#region Constructor
public Repository(DataContext context)
{
_objectSet = context.GetTable<T>();
}
#endregion
public virtual void Add(T entity)
{
_objectSet.InsertOnSubmit(entity);
}
}
都市リポジトリ:
public class CityRepository: Repository<City>
{
public CityRepository(DataContext context): base(context)
{
public override void Add(City entity)
{
//Can't publish event here, because Changes
//aren't still submitted to Database
base.Add(entity);
//CityAddedEventArgs e = new CityAddedEventArgs(entity);
//if (this.CityAdded != null)
//this.CityAdded(this, e);
}
}
}
作業単位
public class UnitOfWork : IUnitOfWork
{
private readonly DataContext _context;
public UnitOfWork(DataContext context)
{
_context = context;
}
#region IUnitOfWork Members
public AddressRepository Addresses
{
get
{
if (_addresses == null)
{
_addresses = new AddressRepository(_context);
}
return _addresses;
}
}
public CityRepository Cities
{
get
{
if (_cities == null)
{
_cities = new CityRepository(_context);
}
return _cities;
}
}
public void Save()
{
_context.SubmitChanges();
//Need to Raise event here if an entity is added,
//but don't know which entity is added !
}
}
今。エンティティがデータベースに追加されたとき、つまり UnitOfWork.Save() メソッドでイベントを公開したいと考えています。たとえば、AddressEntity がデータベースに追加された場合、AddressAdded イベントが発生する必要があり、CityEntity がデータベースに追加された場合、CityAdded イベントが発生する必要があります。しかし、どのエンティティがデータベースに追加されたかを SubmitChanges の後でどのように知ることができますか?
イベントを公開する唯一の目的はViewModel
、エンティティがデータベースに追加されたことをEntityViewModel
知らせることです。ObservableCollection<EntityViewModel>