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的更多相关文章

  1. Entity Framework Tutorial Basics(25):Delete Single Entity

    Delete Entity using DBContext in Disconnected Scenario: We used the Entry() method of DbContext to m ...

  2. Entity Framework Tutorial Basics(24):Update Single Entity

    Update Existing Entity using DBContext in Disconnected Scenario: In this chapter, you will learn how ...

  3. Entity Framework Tutorial Basics(20):Persistence in Entity Framework

    Persistence in Entity Framework There are two scenarios when persisting an entity using EntityFramew ...

  4. 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 ...

  5. 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 ...

  6. 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 ...

  7. Entity Framework Tutorial Basics(1):Introduction

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

  8. 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 ...

  9. Entity Framework Tutorial Basics(19):Change Tracking

    Change Tracking in Entity Framework: Here, you will learn how entity framework tracks changes on ent ...

随机推荐

  1. [转载] 最简单的基于FFmpeg的AVDevice例子(读取摄像头)

    =====================================================最简单的基于FFmpeg的AVDevice例子文章列表: 最简单的基于FFmpeg的AVDev ...

  2. UVALive - 4126 Password Suspects (AC自动机+状压dp)

    给你m个字符串,让你构造一个字符串,包含所有的m个子串,问有多少种构造方法.如果答案不超过42,则按字典序输出所有可行解. 由于m很小,所以可以考虑状压. 首先对全部m个子串构造出AC自动机,每个节点 ...

  3. 二、python沉淀之路~~字符串属性(str)

    1.capitalize的用法:即将输出字符串首字母大写 test = "heLLo" v = test.capitalize() print(v) 结果:Hello. 2.cas ...

  4. c#生成唯一编号方法记录,可用数据库主键 唯一+有序

    数据库主键目前主要有两种: a.自增数值型 优:占用空间小,插入快,有序对索引友好,易懂 缺:多数据库迁移会有重复键值问题,有可能爆表 b.GUID 优:多数据库唯一 缺:占用空间大,无序对索引不友好 ...

  5. 程序员转项目管理之考证PMP

    转行项目经历是IT人的出路之一,最近身边有好几个同事都在备考PMP,从个人未来职业发展来看,如果你有将来转行项目管理的想法,应该去尝试考一下PMP. PMP(Project Management Pr ...

  6. [转]java 中的序列化是什么意思?有什么好处?

    1.序列化是干什么的? 简单说就是为了保存在内存中的各种对象的状态,并且可以把保存的对象状态再读出来.虽然你可以用你自己的各种各样的方法来保存Object States,但是Java给你提供一种应该比 ...

  7. Linux cciss磁盘设备文件的说明

    在某些机器上安装Linux后,发现在/dev目录下找不到hda.hdb.sda等磁盘设备文件,那么挂接的磁盘 在哪里呢?使用mount命令查看挂接设备情况,发现磁盘文件在.dev\cciss目录下,并 ...

  8. Java基础--单例类创建和测试

    单例模式的主要作用是保证在Java程序中,某个类只有一个实例存在.单例模式有很多好处,它能够避免实例对象的重复创建,不仅可以减少每次创建对象的时间开销,还可以节约内存空间:能够避免由于操作多个实例导致 ...

  9. 删除pool error的解决方法

    标签(空格分隔): ceph,ceph运维,pool 问题描述: 删除pool的时候提示下面的错误: [root@node3 ~]# ceph osd pool delete ecpool ecpoo ...

  10. 在U盘分区安装Kali并引导live CD 教程以及常见的注意事项

    Kali Linux作为强大的全能渗透系统,把它制成Live CD基本算是必备技能了,但是官方提供的文档虽然简单,但是整个U盘都会被占用,确实是有点可惜,结合网上提供的一些思路加上自己的经验,向大家讲 ...