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 ...
随机推荐
- yii2.0缓存的使用
1.片段缓存(针对于视图中的某部分进行缓存): <?php 设置有效时间 $time=15; 缓存依赖,存入文件.当文件内容发生改变是才会刷新新内容 $dependecy=[ 'class'=& ...
- tensorflow 学习笔记-1
http://www.jianshu.com/p/e112012a4b2d 参考的网站 -------------------------------------------------------- ...
- golang实现模拟键盘按键
公司前段时间要我写个小项目需要可以局域网内一个ipad控制另一台pc上的键盘输入,github上找了找,居然有个robotgo库这么神级的存在,感觉go的库真是越来越多了,虽然大部分都是第三方的.ht ...
- 转载:电商项目完成的BUG调查原因和解决方案
转载: http://blog.csdn.net/yuexianchang/article/details/73197874
- Spark入门实战系列
转自:http://www.cnblogs.com/shishanyuan/p/4699644.html 这一两年Spark技术很火,自己也凑热闹,反复的试验.研究,有痛苦万分也有欣喜若狂,抽空把这些 ...
- Tomcat的安装与环境配置
首先,下载地址为:http://tomcat.apache.org/,在左侧的列表中找到Download,找到自己要下载的Tomcat的版本.我下载的是Tomcat 7. 进入后出现如上右图界面.我选 ...
- vbs查看系统开关机时间
如何获取XP系统的开机时间? 下面给出两种代码,保存到扩展名为vbs的文件中.具体哪个请根据自己需求决定. 一:根据系统日志,查看开机时间和关机时间,---- 使用弹出对话框的形式 Set WMI = ...
- 开放群组架构TOGAF
作于一个架构师尤其是企业架构师来说,丰富的理论知识可以帮助他在架构规划及管理过程中站在更高的角度去看待问题,历史发展原因有很多已成体系的架构理论,TOGAF是近年来比较接地气的,受到了政府和银行业的重 ...
- The Salt Master has rejected this minion's public key!
salt查看日志: salt --log-level=all "10.199.165.244" state.highstate 进入调试模式: salt-minion -l deb ...
- 蓝桥杯 基础练习 BASIC-23 芯片测试
基础练习 芯片测试 时间限制:1.0s 内存限制:512.0MB 问题描述 有n(2≤n≤20)块芯片,有好有坏,已知好芯片比坏芯片多. 每个芯片都能用来测试其他芯片.用好芯片测试其他芯片时, ...