I have this code
DivisionService divService = new DivisionService();
Division div = divService.FindById(10);
Counter c = new Counter(div);
unitOfWork.CounterRepository.Add(c);
unitOfWork.SaveChanges();
This code is supposed to add a new Counter
and not to add a new Division
since the division is retrieved from the database, but what happens is that it adds both. Any idea what could be the problem?
EDIT
Below is the class 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();
}
}
Here is also the BaseCounterRepository
that the CounterRepository
and CounterService
wraps
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
}
}
}