zoukankan      html  css  js  c++  java
  • ef4.0和ef5.0增删改查的写法区别及执行Sql的方法

    public T AddEntity(T entity) 
    {
        //EF4.0的写法  
        添加实体
        //db.CreateObjectSet<T>().AddObject(entity);
        //EF5.0的写法
        db.Entry<T>(entity).State = EntityState.Added;
        //下面的写法统一
        db.SaveChanges();
        return entity;
    }
    public bool UpdateEntity(T entity)
    {
        //EF4.0的写法
        //db.CreateObjectSet<T>().Addach(entity);
        //db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
        //EF5.0的写法 
       db.Set<T>().Attach(entity); 
       db.Entry<T>(entity).State = EntityState.Modified; 
       return db.SaveChanges() > 0; 
    }
    public bool DeleteEntity(T entity)
    {
        //EF4.0的写法 
       //db.CreateObjectSet<T>().Addach(entity);
       //db.ObjectStateManager.ChangeObjectState(entity, EntityState.Deleted);
       //EF5.0的写法
       db.Set<T>().Attach(entity);
       db.Entry<T>(entity).State = EntityState.Deleted;
       return db.SaveChanges() > 0;
    }

    public IQueryable<T> LoadEntities(Func<T, bool> whereLambda)
    {
        //EF4.0的写法
        //return db.CreateObjectSet<T>().Where<T>(whereLambda).AsQueryable();
        //EF5.0的写法
        return db.Set<T>().Where<T>(whereLambda).AsQueryable();
    }
    执行SQL语句
    //EF4.0的写法
    //int ExcuteSql(string strSql, ObjectParameter[] parameters);
    return EFContextFactory.GetCurrentDbContext().ExecuteFunction(strSql, parameters);
    //EF5.0的写法
     int ExcuteSql(string strSql, DbParameter[] parameters);
    return DEFContextFactory.GetCurrentDbContext().ExecuteSqlCommand(strSql, parameters);
  • 相关阅读:
    PHP数组(数组正则表达式、数组、预定义数组)
    面向对象。OOP三大特征:封装,继承,多态。 这个讲的是【封存】
    uvalive 3938 "Ray, Pass me the dishes!" 线段树 区间合并
    LA4329 Ping pong 树状数组
    HDU 1257 最少拦截系统
    HDU 1260 Tickets
    codeforce 621D
    codeforce 621C Wet Shark and Flowers
    codeforce 621B Wet Shark and Bishops
    codeforce 621A Wet Shark and Odd and Even
  • 原文地址:https://www.cnblogs.com/houzuofeng/p/3621459.html
Copyright © 2011-2022 走看看