EF Code first + Delete Child Object from Parent?
- by ebb
I have a one-to-many relationship between my table Case and my other table CaseReplies. I'm using EF Code First and now wants to delete a CaseReply from a Case object, however it seems impossible to do such thing because it just tries to remove the CaseId from the specific CaseReply record and not the record itself..
short: Case just removes the relationship between itself and the CaseReply.. it does not delete the CaseReply.
My code:
// Case.cs (Case Object)
public class Case
{
[Key]
public int Id { get; set; }
public string Topic { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
public Guid UserId { get; set; }
public virtual User User { get; set; }
public virtual ICollection<CaseReply> Replies { get; set; }
}
// CaseReply.cs (CaseReply Object)
public class CaseReply
{
[Key]
public int Id { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
public int CaseId { get; set; }
public Guid UserId { get; set; }
public virtual User User { get; set; }
public virtual Case Case { get; set; }
}
// RepositoryBase.cs
public class RepositoryBase<T> : IRepository<T> where T : class
{
public IDbContext Context { get; private set; }
public IDbSet<T> ObjectSet { get; private set; }
public RepositoryBase(IDbContext context)
{
Contract.Requires(context != null);
Context = context;
if (context != null)
{
ObjectSet = Context.CreateDbSet<T>();
if (ObjectSet == null)
{
throw new InvalidOperationException();
}
}
}
public IRepository<T> Remove(T entity)
{
ObjectSet.Remove(entity);
return this;
}
public IRepository<T> SaveChanges()
{
Context.SaveChanges();
return this;
}
}
// CaseRepository.cs
public class CaseRepository : RepositoryBase<Case>, ICaseRepository
{
public CaseRepository(IDbContext context)
: base(context)
{
Contract.Requires(context != null);
}
public bool RemoveCaseReplyFromCase(int caseId, int caseReplyId)
{
Case caseToRemoveReplyFrom = ObjectSet.Include(x => x.Replies).FirstOrDefault(x => x.Id == caseId);
var delete = caseToRemoveReplyFrom.Replies.FirstOrDefault(x => x.Id == caseReplyId);
caseToRemoveReplyFrom.Replies.Remove(delete);
return Context.SaveChanges() >= 1;
}
}
Thanks in advance.