保存UnitOfWork时引发EntityAddedEvent

时间:2012-11-09 12:30:21

标签: c# wpf mvvm repository-pattern unit-of-work

我正在使用UnitOfWork和Repository Pattern。该体系结构是MVVM,LINQ-to-SQL类直接作为模型。以下代码段显示了Generic Repository,A Sample(City Repository)和UnitOfWork Class。

通用存储库:

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);

             }
       }
 }

工作单位

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>

1 个答案:

答案 0 :(得分:1)

在Save方法中,您可以先将添加的元素放在列表中,然后在SubmitChanges()之后使用该列表。类似的东西(我现在没有Visual Sutdio所以它可能无法编译):

    public void Save()
    {
        var inserts = _context.GetChangeSet().Inserts.ToList();

        _context.SubmitChanges();

        foreach(var entityAdded in inserts)
        {
            //raise event
        }
    }