CRUD Operation in Connected Scenario:

CRUD operation in connected scenario is a fairly easy task because the context automatically tracks the changes that happened in the entity during its lifetime, provided AutoDetectChangesEnabled is true, by default.

Make sure that you have created an Entity Data Model as shown in the Create Entity Data Modelsection for SchoolDB sample database.

The following example shows how you can add, update, and delete an entity in the connected scenario (within the scope of context), which in turn will execute insert, update, and delete commands on the database. Context will automatically detect the changes and update the state of an entity.

using (var context = new SchoolDBEntities())
{
var studentList = context.Students.ToList<Student>(); //Perform create operation
context.Students.Add(new Student() { StudentName = "New Student" }); //Perform Update operation
Student studentToUpdate = studentList.Where(s => s.StudentName == "student1").FirstOrDefault<Student>();
studentToUpdate.StudentName = "Edited student1"; //Perform delete operation
context.Students.Remove(studentList.ElementAt<Student>()); //Execute Inser, Update & Delete queries in the database
context.SaveChanges();
}

Note: If context.Configuration.AutoDetectChangesEnabled = false then context cannot detect changes made to existing entities so do not execute update query. You need to call context.ChangeTracker.DetectChanges() before SaveChanges() in order to detect the edited entities and mark their status as Modified.

Context detects adding and deleting entity, when the operation is performed only on DbSet. If you perform add and delete entity on a separate collection or list, then it won't detect these changes.

The following code will NOT insert or delete student. It will only update the student entity because we are adding and deleting entities from the List and not from DbSet.

using (var context = new SchoolDBEntities())
{
var studentList = context.Students.ToList<Student>(); //Add student in list
studentList.Add(new Student() { StudentName = "New Student" }); //Perform update operation
Student studentToUpdate = studentList.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();
studentToUpdate.StudentName = "Edited student1"; //Delete student from list
if (studentList.Count > )
studentList.Remove(studentList.ElementAt<Student>()); //SaveChanges will only do update operation not add and delete
context.SaveChanges();
}

Learn how to do the CRUD operation in the disconnected scenario in the next sections.

Entity Framework Tutorial Basics(21):CRUD Operation in Connected Scenario的更多相关文章

  1. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  2. Entity Framework Tutorial Basics(4):Setup Entity Framework Environment

    Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...

  3. Entity Framework Tutorial Basics(43):Download Sample Project

    Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...

  4. Entity Framework Tutorial Basics(42):Colored Entity

    Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that ...

  5. Entity Framework Tutorial Basics(41):Multiple Diagrams

    Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...

  6. Entity Framework Tutorial Basics(37):Lazy Loading

    Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...

  7. Entity Framework Tutorial Basics(36):Eager Loading

    Eager Loading: Eager loading is the process whereby a query for one type of entity also loads relate ...

  8. Entity Framework Tutorial Basics(34):Table-Valued Function

    Table-Valued Function in Entity Framework 5.0 Entity Framework 5.0 supports Table-valued functions o ...

  9. Entity Framework Tutorial Basics(33):Spatial Data type support in Entity Framework 5.0

    Spatial Data type support in Entity Framework 5.0 MS SQL Server 2008 introduced two spatial data typ ...

随机推荐

  1. CodeForces - 827A:String Reconstruction (基础并查集)

    Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun ...

  2. Apache POI实现excel导出

    链接:http://poi.apache.org/ Excel数据导出步骤: 使用poi 完成账户数据的导出功能 导入poi  jar包并添加到classpath中 1.查询数据 2.定义导出头 St ...

  3. LeetCode Sum of Square Numbers

    原题链接在这里:https://leetcode.com/problems/sum-of-square-numbers/description/ 题目: Given a non-negative in ...

  4. 跨域问题解决方案之chrome插件

    地址: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkki ...

  5. python爬虫彩票案例,并自动发微信

    import requests from bs4 import BeautifulSoup import itchat import time,datetime all = [{1, 2, 3, 7, ...

  6. MQTT事件回调流程

    TLS 如下强调: 1.每个IOT设备应该有一对独有的公钥/私钥 2.SERVER的认证通过SERVER的"root certificate" SSL产生过程: $ openssl ...

  7. 如果有多个集合的迭代处理情况【使用MAP】

    在SQL开发过程中,动态构建In集合条件查询是比较常见的用法,在Mybatis中提供了foreach功能,该功能比较强大,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内.它也允许你指 ...

  8. Day3-Python基础3--函数参数及调用

    一.return返回值 return的两个作用: 1)需要用一个变量来接受程序结束后返回的结果 2)它是作为一个结束符,终止程序运行 def test(): print("我是return前 ...

  9. maven学习7 settings.xml解析

    maven的配置文件settings.xml存在于两个地方: 1.安装的地方:${M2_HOME}/conf/settings.xml 2.用户的目录:${user.home}/.m2/setting ...

  10. Celery-4.1 用户指南: Canvas: Designing Work-flows(设计工作流程)

    签名 2.0 版本新特性. 刚刚在calling 这一节中学习了使用 delay 方法调用任务,并且通常这就是你所需要的,但是有时候你可能想将一个任务调用的签名传递给另外一个进程或者作为另外一个函数的 ...