zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——解码篇:(二)用ffmpeg解码音频
    ffmpeg音频播放代码示例-avcodec_decode_audio4
    一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——解码篇:(一)用ffmpeg解码视频
    一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——收流篇:(二)示例
    Oracle加密表空间进行数据加密的示例
    Oracle TDE的数据加密示例并用logminer验证加密效果
    Oracle登录操作系统验证和密码文件验证
    使用dbms_crypto包加密关键列数据
    使用文件模拟ASM磁盘
    演示save point及自治事务的用处
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5649106.html
Copyright © 2011-2022 走看看