zoukankan      html  css  js  c++  java
  • Entity Framework

    基本用法(CRUD)

    1.插入:

    // Create entity context
    MyTest2Entities mt = new MyTest2Entities();
    
    // Create an instance of SClass
    SClass sc = new SClass();
    sc.AddTime = DateTime.Now;
    sc.Name = "Class 1";
    
    // Insert the instance into database
    mt.SClasses.Add(sc);
    int count = mt.SaveChanges();
    Console.WriteLine(count.ToString());

    2.修改:

    // Create entity context
    MyTest2Entities mt = new MyTest2Entities();
    
    // Create an instance need modified
    SClass sc = new SClass();
    sc.Id = 2;
    sc.Name = "Kyle";
    sc.AddTime = DateTime.Now;
    
    // Attach the entity need modified
    mt.SClasses.Attach(sc);
    
    // Modify execute status
    mt.Entry(sc).State = System.Data.Entity.EntityState.Modified;
    mt.SaveChanges();

    3.查询:

    #region Multiple record query
    MyTest2Entities mt = new MyTest2Entities();
    
    var classes = from c in mt.SClasses
                    where c.Id < 10
                    select c;
    
    foreach (var item in classes)
    {
        Console.WriteLine(item.Name);
    }
    #endregion
    
    #region Single record query
    MyTest2Entities mt = new MyTest2Entities();
    var single = (from c in mt.SClasses
                    where c.Id == 1
                    select c).FirstOrDefault();
    
    if (single != null)
        Console.WriteLine(single.Name);
    #endregion

    4.删除:

    MyTest2Entities mt = new MyTest2Entities();
    
    SClass sc = new SClass();
    sc.Id = 2;
    
    mt.SClasses.Attach(sc);
    mt.Entry(sc).State = System.Data.Entity.EntityState.Deleted;
    mt.SaveChanges();

    获取主键:

    // TestEntities 继承于 DbContext
    using (var db = new TestEntities())
    {
        var objectContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext;
        // Brand 是其中一个表
        ObjectSet<Brand> set = objectContext.CreateObjectSet<Brand>();
        //Act
        IEnumerable<string> keyNames = set.EntitySet.ElementType.KeyMembers.Select(k => k.Name);
        Console.WriteLine("{0}", string.Join(",", keyNames.ToArray()));
    }
  • 相关阅读:
    MQCONN failed (Reason = 2277)
    MQ打开队列模式 input和input_exclusive
    mq 消息最大长度 最大是100M
    Easyui Datagrid的Rownumber行号显示问题
    ajax请求时session已过期处理方案
    seafile Windows Memcached
    seafile 接口频度控制
    你的旧船票能否搭上这艘巨轮?——解读近5年大数据产业发展规划
    第一章 输入/输出知识
    It looks like you don't have a C compiler and make utility installed. 错误
  • 原文地址:https://www.cnblogs.com/jizhiqiliao/p/10905614.html
Copyright © 2011-2022 走看看