我有这段代码
DivisionService divService = new DivisionService();
Division div = divService.FindById(10);
Counter c = new Counter(div);
unitOfWork.CounterRepository.Add(c);
unitOfWork.SaveChanges();
这段代码应该添加一个新的Counter
,而不是添加一个新的Division
,因为从数据库中检索了分区,但是会发生什么,它会添加两者。知道可能是什么问题吗?
修改
以下是课程Counter
public class Counter : BaseCounter
{
Division division;
private Counter()
{
}
public Counter(Division division)
{
this.division = division;
}
public Division Division
{
get
{
return division;
}
private set
{
division = value;
}
}
public override string GetNumber()
{
return number.ToString();
}
}
以下BaseCounterRepository
和CounterRepository
包裹的CounterService
public abstract class BaseCounterRepository<T> where T : BaseCounter
{
protected MyContext context;
public BaseCounterRepository()
{
this.context = new MyContext();
}
public BaseCounterRepository(MyContext context)
{
this.context = context;
}
public virtual T FindById(int id)
{
T result = default(T);
try
{
result = (T)context.Set<T>().Find(id);
}
catch (Exception ex)
{
// handle execption
}
return result;
}
public virtual T Add(T obj)
{
try
{
T result = context.Set<T>().Add(obj);
return result;
}
catch (Exception ex)
{
// handle execption
}
}
public virtual void DeleteById(int id)
{
try
{
T entity = context.Set<T>().Find(id);
context.Set<T>().Remove(entity);
}
catch (Exception ex)
{
// handle execption
}
}
}
答案 0 :(得分:0)
这个question给了我答案的灵感,结果发现我每个UnitOfWork
课程使用不同的DBContext
(因此Service
},这就是为什么Division
类中的DivisionService
看起来是CounterService
类及其DBContext
的新内容,因此重新插入。