【发布时间】:2014-07-04 17:50:10
【问题描述】:
我有以下结构的域对象
public class Country : Entity
{
public Country()
{
States=new List<State>();
}
public string CountryName { get; set; }
public string CountyCode { get; set; }
public virtual ICollection<State> States { get; private set; }
public State GetStateById(int stateId)
{
return States.FirstOrDefault(x => x.Id == stateId);
}
public void DeleteState(int stateId)
{
var state = GetStateById(stateId);
if(state==null) return;
States.Remove(state);
}
}
这里我使用 DeleteState 方法删除一个状态对象(它是一个国家的子对象)。
我有具有以下结构的存储库(它是一个聚合根)
public class CountryRepository : Repository<Country>, ICountryRepository
{
public CountryRepository(IErpBaseUnitOfWork unitOfWork)
: base(unitOfWork)
{
}
// Unnecessary codes removed
public void Modify<TEntity>(TEntity item)
where TEntity : class
{
//this operation also attach item in object state manager
Entry<TEntity>(item).State = EntityState.Modified;
}
}
和 unitofwork.commit 调用 Context.SaveChanges
业务层
public class CountryAppService : ICountryAppService
{
private readonly ICountryRepository _countryRepository;
public CountryAppService(ICountryRepository countryRepository)
{
_countryRepository = countryRepository;
}
public CountryDto RemoveState(int stateId, int countryid)
{
var country = _countryRepository.FindById(countryid);
if (country == null || country.Status == false) throw new ApplicationOperationException(Messages.Validation_CountryInInvalidState) { HttpCode = 400 };
country.DeleteState(stateId);
_countryRepository.Modify(country);
_countryRepository.UnitOfWork.Commit();
return country.ProjectedAs<CountryDto>();
}
}
这里我通过从集合中删除对象来删除状态对象,但 EF 会因为存在孤立状态而生成错误,我的问题是如何通过从集合中删除来删除状态。需要考虑的关键点
1.) 我的领域模型对 EF 或其相关技术一无所知,因此在 Domian 层和业务层中包含少量 Ef 相关代码并不是一个好主意 2.) 我正在将 Db Context 与 CodeFirst 一起使用,
处理此类情况的最佳做法是什么
【问题讨论】:
-
你解决过这个问题吗?
标签: c# .net asp.net-mvc entity-framework ef-code-first