dir.by  
Поиск >>

Компьютер, программы
→
Entity Framework (EF5, EF6) for working with a C database#
 Управление транзакциями в Entity Framework 
посмотрели 8877 раз
обновлено: 3 Augusta 2018
В Entity Framework приложении мы можем управлять транзакциями.

Транзакции применяются для того, чтобы выполнить последовтельность операций (выполнять одну операцию за другой).
Если при выполнении какой-то операции происходит ошибка, то все предыдущии операции откатываются (отменяются).
То есть или выполнятся все операции без ошибок или не выполнится ни одной операции(если произошла хоть одна ошибка).

Управление транзакциями:
Пример:
Создание транзакции
var transaction = db.Database.BeginTransaction();
Операция1 с базой данных
Операция2 с базой данных
...
db.Database.ExecuteSqlCommand(@"UPDATE Books SET Price = 23 WHERE Name = 'Три кота'");
db.Books.Add(new Book { Name = "Дом", Price = 78 });

...
Коммит (завершение) транзакции
transaction.Commit();
Откат (отмена транзакции)
transaction.Rollback();
Шаг 1. Создаем новое приложение
Шаг 2. Напишем код
  C#     В файле Program.cs напишем код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data.Entity;

namespace ConsoleApplication1
{
     // сущность (соответствует таблице в базе данных)
     public class Book
     {
          public int Id { get; set; }
          public string Name { get; set; }
          public int Price { get; set; }
     }

     // Контекст данных
     class UserContext : DbContext
     {
          public UserContext() : base("MyConnection1")
          { }

          public DbSet<Book> Books { get; set; }
     }

     // Вход программы
     class Program
     {
          static void Main(string[] args)
          {
               // create db context
               using (UserContext db = new UserContext())
               {
                    // создаем транзакцию
                    using (var transaction = db.Database.BeginTransaction())
                    {
                         try
                         {
                              // операция 1
                              db.Database.ExecuteSqlCommand(@"UPDATE Books SET Price = 23 WHERE Name = 'Три кота'");

                              // операция 2
                              db.Books.Add(new Book { Name = "Дом", Price = 78 });

                              // операция 3
                              db.SaveChanges();

                              // Завершение транзакции
                              transaction.Commit();
                         }
                         catch (Exception ex)
                         {
                              // отмена транзакции
                              transaction.Rollback();
                         }
                    }
    
                    // покажем на экране
                    foreach(var item in db.Books)
                    {
                         Console.WriteLine("Name={0}, Price={1}", item.Name, item.Price);
                    }
               }
          }
     }
}
Результат примера
 
← Previous topic
SQL Commands in Entity Framework
 
Next topic →
What is <connectionStrings> a .config file for Entity Framework (EF5, EF6)
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" на технику Dreame в Беларуси с 17 по 30 ноября 2026 года – две недели скидок до 3400 рублей
 
• What is Entity Framework?
Types in Entity Framework
• Entity Framework Type Conversion, Table Naming Conventions
• Foreign Key and Cascade Deletion
• DateTime & Date & Time Only in the Entity Framework
Code First
• Code First. We"re writing a C# class. Entity Framework uses our C# class → to create and populate a table in the database
• Auto Code First. Entity Framework creates a C# class from an existing table in the → database
Database First
• Database First. Entity Framework creates a C# class from an existing table in the → database
Model First
• Model First. We create a model in Visual Studio. Using the Entity Framework model, → creates C# classes and a Database
Working with data
• Iterating over data in the Entity Framework
• Adding Data to the Entity Framework
• Modifying (editing) data in the Entity Framework
• Deleting data in the Entity Framework
Database initialization and migration
• Initialize the database in the Entity Framework. DropCreateDatabaseAlways allows you to repopulate the database with each new run
• Performing a Database Migration to Entity Framework (if someone has already made a cs migration file, and I want to update the database on my computer, I perform the migration, that is, call EntityFramework\Update-Database)
• Creating and performing a Database migration to Entity Framework (I changed the c# class, then call EntityFramework\add-migration, i.e. the cs file with the migration code is automatically added to the project, then call EntityFramework\Update-Database, i.e. the migration file is executed and the database is changed)
SQL in Entity Framework
• SQL Commands in Entity Framework
Transactions in the Entity Framework
• Managing Transactions in the Entity Framework
Additional topics, questions
• What is <connectionStrings> a .config file for Entity Framework (EF5, EF6)
• When EntityFrameworkUpdate-Database is called, the error "System.Data.SqlClient.SqlException (0x80131904) is thrown. A network-related or instance-specific error occurred while establishing a connection to SQL Server. "
• When calling EntityFrameworkUpdate-Database, the error "Your startup project "..." doesn"t reference Microsoft.EntityFrameworkCore.Design"
WWW Sites to Learn Entity Framework
• Sites to learn Entity Framework

  Ваши вопросы присылайте по почте: info@dir.by