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 ...
随机推荐
- java入门学习(1)一简介及其基础特点
分类: java基础 1.为什么java如此流行,为什么历史选择了它? 因为它拥有全新的编程思想,更接近人们的语言习惯,由于其编译器把代码编译成字节码,然后再不同的平台上运行分别用不同的虚拟机去解释字 ...
- Office 2007在安装过程中出错
1, 可能是因为c:\program files\common files\microsoft Shared\web server Extensions\40\bin目录下缺少Fp4autl.dll, ...
- 《Javascript高级程序设计》阅读记录(七):第七章
<Javascript高级程序设计>中,2-7章中已经涵盖了大部分精华内容,所以摘录到博客中,方便随时回忆.本系列基本完成,之后的章节,可能看情况进行摘录. 这个系列以往文字地址: < ...
- NOIp2018集训test-10-24(am&pm)
李巨连续AK三场了,我跟南瓜打赌李巨连续AK七场,南瓜赌李巨连续AK五场. DAY1 T1 qu 按题意拿stack,queue和priority_que模拟即可.特判没有元素却要取出的情况. T2 ...
- HttpContext是干什么的
这是MSDN对HttpContext的说明: HttpContext 类:封装有关个别 HTTP 请求的所有 HTTP 特定的信息. (网上说是上下文信息,啥又叫上下文呢?个人感觉说的不 ...
- 使用POI导出excel进阶篇
进阶篇就是涉及到合并单元格了.就是某一列相同的单元格需要合并为一个,并分为多个sheet. 效果如图: 直接上代码,需要提供的数据自己搞,传到工具类里面就好. JcExcelVoSuper.java ...
- laravel 接收json串
在做项目的时候发现 用平时的$request->all() 无法获取到请求值 然后这样解决了 但是还是不知道原因 学习源头: http://www.cnblogs.com/anjuncc/p/5 ...
- 接口方式[推荐]/动态SQL语句
MVC目录结构: Src -- com.shxt.servlet[控制层] --com.shxt.service[业务逻辑层] --com.shxt.model[实体Bean,用来承载数据] --co ...
- 蓝桥杯 算法训练 ALGO-156 表达式计算
算法训练 表达式计算 时间限制:1.0s 内存限制:256.0MB 问题描述 输入一个只包含加减乖除和括号的合法表达式,求表达式的值.其中除表示整除. 输入格式 输入一行,包含一个表达式. 输 ...
- AllowsTransparency和WebBrowser兼容性问题解决方案
AllowsTransparency和System.Windows.Controls.WebBrowser兼容性问题,能看这篇文章,所以原因也不用多说:最根本的就是因为MS对win32底层的WebBr ...