尝试在CTP5中删除POCO对象时遇到问题 [英] Having trouble trying to Delete a POCO object in CTP5

查看:93
本文介绍了尝试在CTP5中删除POCO对象时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨大家好,

我在尝试使用我的CTP5代码删除POCO对象时遇到问题。

I'm having a problem trying to delete a POCO object with my CTP5 code.

我'我将从我的删除方法开始,然后再进行整合测试。第一个 整合 测试通过/工作,第二个没有。

I'll start out with my Delete method and then both Integration Tests. First Integration Test passes/works, second doesn't.


public class GenericRepository<T> : IRepository<T> where T : class
{
  public GenericRepository(DbContext unitOfWork)
  {
    Context = unitOfWork;
  }

  ...

  public void Delete(T entity)
  {
    if (entity == null)
    {
      throw new ArgumentNullException("entity");
    }

    if (Context.Entry(entity).State == EntityState.Detached)
    {
      Context.Entry(entity).State = EntityState.Deleted;
    }
    Context.Set<T>().Remove(entity);
  }

  ...
}

推荐答案

<好的 - 我认为这是一个可以接受的答案。我希望EF团队的某个人能够看到我的逻辑是否疯狂。

Ok - I think this is an acceptable answer now. I would love someone on the EF team to see if my logic is crazy.

 


public void Delete(T entity)
{
  if (entity == null)
  {
    throw new ArgumentNullException("entity");
  }
      
  // Because we're using Generics, i need to use some reflection and some expression building magic to make the predicate, on the fly.
  // If this was not a generic repo, then just hard code the expression;. eg. x => x.UserId = 1 .. etc.
  var predicate = GetPrimaryKeyLambdaExpression(IdentityPropertyValue(entity));

  // Does this object already exist in the graph?
  var attachedEntity = Context.Set<T>().Local.FirstOrDefault(predicate);

  if (attachedEntity != null)
  {
    // Entity already in object graph - remove entity.
    Context.Set<T>().Remove(attachedEntity);  
  }
  else
  {
    // Entity not in object graph, attach and set EntityState to Deleted.
    Context.Entry(entity).State = EntityState.Deleted;
  }
}


这篇关于尝试在CTP5中删除POCO对象时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆