EntityFramework 学习 一 Add New Entity using DBContext in Disconnected Scenario

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; }
}

 

 

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; }
}

 

 

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();
        }
    }
}

 

首先创建新的Student对象并设置StudentName为bill

其次创建新的Context上下文,并把新实体添加到Students的EntitySet中

最后调用SaveChanges方法,将在数据库中执行如下操作 

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'

 

上面也可以用如下方法添加实体

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();
        }
    }
}

 

posted @ 2017-03-25 21:24  蓝平凡  阅读(299)  评论(0编辑  收藏  举报