zoukankan      html  css  js  c++  java
  • Entity Framework Tutorial Basics(24):Update Single Entity

    Update Existing Entity using DBContext in Disconnected Scenario:

    In this chapter, you will learn how to update a single entity in a disconnected scenario.

    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 update a 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 example shows how to update a Student entity in the disconnected scenario:

    Student stud;
    //1. Get student from DB
    using (var ctx = new SchoolDBEntities())
    {
        stud = ctx.Students.Where(s => s.StudentName == "New Student1").FirstOrDefault<Student>();
    }
    
    //2. change student name in disconnected mode (out of ctx scope)
    if (stud != null)
    {
        stud.StudentName = "Updated Student1";
    }
    
    //save modified entity using new Context
    using (var dbCtx = new SchoolDBEntities())
    {
        //3. Mark entity as modified
        dbCtx.Entry(stud).State = System.Data.Entity.EntityState.Modified;     
            
        //4. call SaveChanges
        dbCtx.SaveChanges();
    }

    As you see in the above code snippet, we are doing the following steps:

    1. Get the existing student from DB.
    2. Change the student name out of Context scope (disconnected mode)
    3. Pass the modified entity into the Entry method to get its DBEntityEntry object and then mark its state as Modified
    4. Call SaveChanges() method to update student information into the database.

    SaveChanges will send the following update query to the database:

    exec sp_executesql N'update [dbo].[Student]
    set [StudentName] = @0, [StandardId] = @1
    where ([StudentID] = @2)',N'@0 varchar(50),
    @1 int,@2 int',@0='Updated Student1',@1=299,@2=267

    In this way, we can easily update a single entity using DBContext in the disconnected mode.

    DbContext.Entry method returns an instance of DBEntityEntry for a specified Entity. An instance of DbEntityEntry class providea access to information about a given entity and its state. You can change the state of an entity to Added, Updated, or Deleted.

    In the next chapter you will learn how to delete a single entity in the disconnected mode.

  • 相关阅读:
    requests模块使用
    如何在vue中调用百度地图
    VS Code 改变默认文字编码 为utf-8
    清理电脑C盘的方法
    安装最新版本的angular-cli的命令行代码
    微信小程序发布后查看实时日志
    微信小程序 POST传值跳坑
    App唤起微信小程序和回调
    微信小程序判断进入小程序的入口(场景值)
    微信小程序参数传递获取当前页面的url和参数
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5649118.html
Copyright © 2011-2022 走看看