【问题标题】:EF 6 Insert,Update and delete with generic methodEF 6 使用通用方法插入、更新和删除
【发布时间】:2017-06-24 03:10:57
【问题描述】:

我创建了 Web 服务 asp API 宽度 EF 6 来连接 sql server .. 我创建了通用方法来执行插入 & 更新 & 删除 .. 方法是

    protected enum ExecuteActions
    {
        Insert,
        Update,
        Delete
    }
protected ResponseResult Execute<T>(T entity,ExecuteActions exAction) where T:class
{
      var model = db.Set<T>();
      switch (exAction)
                {
                    case ExecuteActions.Insert:
                        model.Add(entity);
                        break;
                    case ExecuteActions.Update:
                        model.Attach(entity);
                        db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                        break;
                    case ExecuteActions.Delete:
                        model.Attach(entity);
                        db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                        break;

                    default:
                        break;
                }
                  db.SaveChanges();    
}

Insert 工作正常,但问题出在 Update 案例中 .. 与某些实体和其他一些实体一起工作的难以理解的事情会引发错误

附加类型为“xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”的实体失败,因为同一类型的另一个实体已经具有相同的主键值。如果图中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。这可能是因为某些实体是新实体,尚未收到数据库生成的键值。在这种情况下,使用“添加”方法或“已添加”实体状态来跟踪图形,然后将非新实体的状态设置为“未更改”或“已修改”。

我找到了一些解决方案,解释说我必须使用(查找)来获取实体而不是更新它..但它与我的工作不兼容..因为我不知道方法中泛型类型的 ID .

我也试过this

在另一个项目中,它通过类似这种方法的方式工作......所以我认为实体框架元素(edmx)有问题......所以我删除它并重新创建它,但什么也没发生

【问题讨论】:

    标签: c# entity-framework generics


    【解决方案1】:

    为您的实体类型创建一个接口,例如:

    public interface IKeyed{
         int KeyValue{get;}
    }
    

    然后让您的实体实现接口,例如:

    public partial class Foo : IKeyed{
         public int KeyValue {get {return this.Id;}}
         public int Id {get; set;}
    }
    

    然后更新您的通用方法签名以将 T 定义为 IKeyed

    protected ResponseResult Execute<T>(T entity,ExecuteActions exAction) 
                                        where T : class, IKeyed
    

    然后参考

    entity.KeyValue 
    

    使用实体框架的“查找”方法时。

    【讨论】:

      猜你喜欢
      • 2019-05-25
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      • 1970-01-01
      相关资源
      最近更新 更多