I am using UnitOfWork along with Repository Pattern. The architecture is MVVM with LINQ-to-SQL Classes directly as Model. Following code snippets show Generic Repository, A Sample(City Repository) and UnitOfWork Class.
Generic Repository:
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);
}
}
CityRepository:
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);
}
}
}
Unit Of Work
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 !
}
}
Now. I want to publish an event when an entity is added to the database i.e. on UnitOfWork.Save() method. For e.g. If AddressEntity is added to the database, AddressAdded event must fire and if CityEntity is added to the database, CityAdded event must fire. But then how would I know after SubmitChanges which entity is added to the database ?
The sole purpose of publishing event is let ViewModel know that an Entity is added to database, and now it can add the EntityViewModel to its ObservableCollection<EntityViewModel>
In your Save method, you can first put the added elements in a list and use that list after the SubmitChanges(). Something like (I don’t have Visual Sutdio right now so it might not compile):