• Entityframework更新数据和插入数据


     1  public bool UpdateEmloyeeInfo(EmployeInfo employeInfo)
     2         {
     3             bool flg = false;
     4             try
     5             {
     6                 using (UserManageDB db = new UserManageDB())
     7                 {
     8                     if (employeInfo.ID > 0)
     9                     {
    10                         EmployeInfo employer = db.EmployeInfo.Single(x => x.ID == employeInfo.ID);                       
    11                         if (employer == null)
    12                             throw new ArgumentOutOfRangeException("employeInfo");
    13                         db.Entry(employer).CurrentValues.SetValues(employeInfo);  //更新实体
    14                         db.SaveChanges();
    15                         flg = true;
    16                     }
    17                     else
    18                     {
    19                         db.EmployeInfo.Add(employeInfo);  //插入实体
    20                         db.SaveChanges();
    21                         flg = true;
    22                     }
    23                 }
    24 
    25                 return flg;
    26             }
    27             catch (Exception)
    28             {
    29 
    30                 throw;
    31             }
    32            
    33         }

    http://www.cnblogs.com/terrysun/archive/2011/07/21/2112840.html

    ADO.NET Entity提共的默认更新数据的方法是:

    1. 先找出要更新的对象(访问一次数据库)
    2. 赋新值
    3. 调用 xxxEntities.SaveChange() 方法(需要再次访问一次数据库)

    一个update操作需要访问2次数据库, 多用户大数据量的环境下这样的性能确实不怎么样, 理想化的操作当然是只进行第2,3步.

    上面的代码是一个扩展方法,任何ObjectContext的子类也就是xxxEntities才可以调用UpdateEntity方法

    1. 第一个参数entity就是要更新的实体对象
    2. 第二个参数entitySetName就是这个实体对象的 Entity Set Name, 通过entity是不能获得到的, 只有在调用UpdateEntity方法时传进来

    以pubs数据库的author表为例, au_id是主键, 下面的代码将会更新author表中au_id为427-17-2319这条数据

    PubsEntities pubsEnt = new PubsEntities();
    Author auth = new Author()
    {
        au_id = "427-17-2319",
        au_lname = "Dull",
        au_fname = "Ann",
        phone = "415 836-7128",
        address = "3410 Blonde St.",
        city = "Palo Alto",
        state = "CA",
        zip = "99999",
        contract = true
    };
    
    pubsEnt.UpdateEntity(auth, pubsEnt.Authors.EntitySet.Name);
    pubsEnt.SaveChanges();

    UpdateEntity方法不足之处是需要传递 pubsEnt.Authors.EntitySet.Name这个参数, 有什么好办法在UpdateEntity内部可以获得这个属值?

    http://www.cnblogs.com/Leo_wl/p/3295648.html

  • 相关阅读:
    利用接口实现简单工厂模式
    简单工厂代码演示
    创建对象的三种方式
    eclipse中常用快捷键
    glog功能介绍
    sublime操作
    caffe train c++
    各层参数介绍,尤其数据层
    LSTM长短期记忆网络
    caffe c++
  • 原文地址:https://www.cnblogs.com/lihongchen/p/3637653.html
Copyright © 2020-2023  润新知