• entity framework 新增,更新,事务


    protected void Button1_Click(object sender, EventArgs e)
    {
    yyEntities _db;
    _db = new yyEntities();

    test t = new test();
    t.testName = this.TextBox1.Text;
    t.testCon = this.TextBox2.Text;
    _db.AddObject("test", t);
    _db.SaveChanges();

    //using (var edm = new yyEntities())
    //{

    // test c = new test { testName = "c2", testCon = "成都市2" };
    // edm.AddObject("test", c);
    // int result = edm.SaveChanges();
    //}

    }

    其中,在代码中,需要注意的是:AddObject方法中参数“entitySetName ”就是指对应实体名称,应该是:“Customers”,而不是“NorthwindEntities.Customers”;

    l 更新:

    using (var edm = new NorthwindEntities())

    {

    Customers addc = edm.Customers.FirstOrDefault(cc => cc.CustomerID == "c2");

    addc.City = "CD";

    addc.ContactName = "cnblogs";

    addc.Country = "CN";

    int result = edm.SaveChanges();

    Assert.AreEqual (result, 1);

    Customers updatec = edm.Customers.FirstOrDefault(cc => cc.CustomerID == "c2");

    Console.WriteLine("CustomerId={0},City={1}", updatec.CustomerID, updatec.City);

    }

    其中,需要注意的是:不能去更新主键,否则会报“System.InvalidOperationException : 属性“xxx”是对象的键信息的一部分,不能修改。”

    l 删除:

    实例代码如下:

    using (var edm = new NorthwindEntities())

    {

    Customers deletec = edm.Customers.FirstOrDefault(cc => cc.CustomerID == "c2");

    edm.DeleteObject(deletec);

    int result = edm.SaveChanges();

    Assert.AreEqual (result, 1);

    Customers c = edm.Customers.FirstOrDefault(cc => cc.CustomerID == "c2");

    Assert.AreEqual (c, null );

    }

    l 事务:

    实例代码如下:

    NorthwindEntities edm = null ;

    System.Data.Common.DbTransaction tran = null ;

    try

    {

    edm = new NorthwindEntities();

    edm.Connection.Open();

    tran = edm.Connection.BeginTransaction();

    Customers cst = edm.Customers.FirstOrDefault(cc => cc.CustomerID == "c#");

    cst.Country = "CN";

    cst.City = "CD";

    edm.SaveChanges();

    tran.Commit();

    }
    catch (Exception ex)
    {
    if (tran != null )
    tran.Rollback();
    throw ex;
    }
    finally
    {
    if (edm != null && edm.Connection.State != System.Data.ConnectionState.Closed)
    edm.Connection.Close();
    }

    //  Skip(N) ,跳过前N条,Take(m)  ,取m条数据

    var c=edm.Customers.OrderBy(c=>c.CustomerId).Skip(30).Take(20);//30-50

  • 相关阅读:
    go 1.14.3安装micro报错处理记录
    关于redis哨兵机制的一些疑问
    TCP中异常关闭的情况记录
    mysql sleep 死锁例子
    ubuntu16.04 安装go
    innodb存储引擎之内存
    ubuntu16.04环境LNMP实现PHP5.6和PHP7.2
    mysql使用存储过程,批量生成测试数据
    mysql 关于字符串搜索的函数
    电脑上的windows键突然失灵了,肿么办
  • 原文地址:https://www.cnblogs.com/yangjinwang/p/4088136.html
Copyright © 2020-2023  润新知