Entity Framework Tutorial Basics(23):Add Single Entity
Add New Entity using DBContext in Disconnected Scenario:
In this chapter you will learn how to add new entity in DbContext in the disconnected scenario, which in turn inserts a new row in a database table.
If you use Database-First approach, then create an Entity Data Model as shown in the previous chapter for SchoolDB sample database. Or, if you use Code-First or Model-First approach, then create entities and context classes. In any case, entities and context classes will look similar.
Here, we will see how to add single Student entity (not entity graph). The following is a Student entity.
using System;
using System.Collections.Generic; public partial class Student
{
public Student()
{
this.Courses = new HashSet<Course>();
} public int StudentID { get; set; }
public string StudentName { get; set; }
public Nullable<int> StandardId { get; set; }
public byte[] RowVersion { get; set; } public virtual Standard Standard { get; set; }
public virtual StudentAddress StudentAddress { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
The following is a context class.
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq; public partial class SchoolDBEntities : DbContext
{
public SchoolDBEntities()
: base("name=SchoolDBEntities")
{
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ } public virtual DbSet<Course> Courses { get; set; }
public virtual DbSet<Standard> Standards { get; set; }
public virtual DbSet<Student> Students { get; set; }
public virtual DbSet<StudentAddress> StudentAddresses { get; set; }
public virtual DbSet<Teacher> Teachers { get; set; }
}
The following code shows how to save a single entity.
class Program
{
static void Main(string[] args)
{
// create new Student entity object in disconnected scenario (out of the scope of DbContext)
var newStudent = new Student(); //set student name
newStudent.StudentName = "Bill"; //create DBContext object
using (var dbCtx = new SchoolDBEntities())
{
//Add Student object into Students DBset
dbCtx.Students.Add(newStudent); // call SaveChanges method to save student into database
dbCtx.SaveChanges();
}
}
}
As you can see in the above code snippet, first, we have created a new Student entity object and set StudentName to 'Bill'. Second, we have created a new DBContext object and added newStudent into Students EntitySet. Third, we called SaveChanges method of DBContext which will execute the following insert query to the database.
exec sp_executesql N'INSERT [dbo].[Student]([StudentName], [StandardId])
VALUES (@0, NULL)
SELECT [StudentID], [RowVersion]
FROM [dbo].[Student]
WHERE @@ROWCOUNT > 0 AND [StudentID] = scope_identity(),@0='Bill'
Alternatively, we can also add entity into DBContext.Entry and mark it as Added which results in the same insert query:
class Program
{
static void Main(string[] args)
{
// create new Student entity object in disconnected scenario (out of the scope of DbContext)
var newStudent = new Student(); //set student name
newStudent.StudentName = "Bill"; //create DBContext object
using (var dbCtx = new SchoolDBEntities())
{
//Add newStudent entity into DbEntityEntry and mark EntityState to Added
dbCtx.Entry(newStudent).State = System.Data.Entity.EntityState.Added; // call SaveChanges method to save new Student into database
dbCtx.SaveChanges();
}
}
}
So, in this way, you can add a new single entity in the disconnected scenario.
In the next chapter, you will learn how to update an existing single entity in the disconnected scenario.
Entity Framework Tutorial Basics(23):Add Single Entity的更多相关文章
- Entity Framework Tutorial Basics(25):Delete Single Entity
Delete Entity using DBContext in Disconnected Scenario: We used the Entry() method of DbContext to m ...
- Entity Framework Tutorial Basics(24):Update Single Entity
Update Existing Entity using DBContext in Disconnected Scenario: In this chapter, you will learn how ...
- Entity Framework Tutorial Basics(20):Persistence in Entity Framework
Persistence in Entity Framework There are two scenarios when persisting an entity using EntityFramew ...
- Entity Framework Tutorial Basics(8):Types of Entity in Entity Framework
Types of Entity in Entity Framework: We created EDM for existing database in the previous section. A ...
- Entity Framework Tutorial Basics(2):What is Entity Framework?
What is Entity Framework? Writing and managing ADO.Net code for data access is a tedious and monoton ...
- Entity Framework Tutorial Basics(26):Add Entity Graph
Add Entity Graph using DbContext: Adding entity graph with all new entities is a simple task. We can ...
- Entity Framework Tutorial Basics(1):Introduction
以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...
- Entity Framework Tutorial Basics(31):Migration from EF 4.X
Migration from Entity Framework 4.1/4.3 to Entity Framework 5.0/6.0 To migrate your existing Entity ...
- Entity Framework Tutorial Basics(19):Change Tracking
Change Tracking in Entity Framework: Here, you will learn how entity framework tracks changes on ent ...
随机推荐
- 团队开发中Git冲突解决
正常来说我们团队协作开发过程中,冲突是常有的事,下面介绍下本人在开发中的解决办法. 冲突的主要原因就是由于我们开发人员在分支的同一位置写入了不一样的代码,然后合并到主干上导致我们冲突. 方法: 当冲突 ...
- VS软件版本号定义、规则和相关的Visual Studio插件
http://blog.csdn.net/cnhk1225/article/details/37500593 软件版本号主要标识了软件的版本,通过其可以了解软件.类库文件的当前版本,使得软件版本控制有 ...
- 非maven项目下载maven的jar
很多时候我们需要jar,可惜项目不是maven的,但是我们只有一个maven的坐标,那怎么办? 比如: <dependencies> <dependency> <grou ...
- OTL调用Oracle存储过程
OTL很早前用过,今天写东西要调存储过程,程序写完了,调试死活通不过,折腾了一早晨. 最后才发现错误,这里总结一下: 1.代码写的不规范. 有个参数后边少写了个“,”以至于总是抱错.而单独写的测试例子 ...
- spark流程跟踪
每个action对应一个job,每个job里面会有很多个阶段(stage),其实每个stage都是一个算子(Operation),可能是transformation,可能是action:但是actio ...
- 一个WCF使用TCP协议进行通协的例子
在解决方案资源管理器中,需要添加两个引用:System.ServiceModel和WCFService.然后双击窗口,在Form_Load事件中编写如下代码: 添加一个应用程序配置文件App.Conf ...
- 【转】hurry_liu 大神STM32移植contiki入门之一:系统介绍和开发环境搭建
前言: 由于项目的原因,需要在LPC1788(STM32 cortex-M3)上面跑contiki. 之前没有涉及到contiki,不知其为何物.不过这个不是难事,做IT的,每每遇到新事物,都不会处理 ...
- [转】LTE整体架构和协议架构概述
1.1 LTE整体架构 LTE(Long Term Evolution,长期演进)是由3GPP(The 3rd Generation Partnership Project,第三代合作伙伴计划)组织制 ...
- java的reflection和introspector
JAVA反射机制是在运行状态中,对于任意一个类,都能够得到这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法:这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制 ...
- postgresql 数据库,模式,表空间的关系
数据库与模式模式(schema)是对数据库(database)逻辑分割在数据库创建的同时,就已经默认为数据库创建了一个模式--public,这也是该数据库的默认模式.所有为此数据库创建的对象(表.函数 ...