dir.by  
  Поиск  
Компьютер, программы
Entity Framework (EF5, EF6) for working with a C database#
 Database First. Entity Framework из существующей таблицы в базе данных → создает C# класс 
посмотрели 12120 раз
обновлено: 4 July 2018
Database First это самый первый подход, который появился в Entity Framework.
Database First создает C# классы по готовым таблицам в Базе данных
План (6 шагов)
Шаг 1. Создаем новое консольное приложение
Шаг 2. Создаем таблицу в Базе данных
Шаг 3. Запускаем Database First (EF Designer from database)
Нажимаем правой клавишей мыши на нашем приложении ConsoleApplication1
Выбираем AddNew ItemADO.NET Entity Data ModelEF Designer from database
Раскроем Tables это все таблицы, имеющиеся в базе данных. В моем случае имеется только одна таблица Book. Отметим все подузлы в ветке Tables.

В поле Model Namespace установим любое имя (я использую по умолчанию). Это имя соединения...
Шаг 4. Смотрим что добавилось
У нас сгенерировалась модель (Model1.edmx) и добавилась в проект.
Модель сгенерировалась по выбранной Базе данных.
Visual Studio отобразила нам схему модели (на картинке).
В моем случае есть только одна таблица Book, поэтому на схеме отображается только одна сущность Book.
Посмотрим какие файлы создались
В проект добавилась новая папка Model1.edmx с файлами:
Book.cs
Entity Framework утилита создала новый класс Book для получения значений из Базы данных
Model1.Context.cs
Для подключения и работой с Базой данных нам нужен контекст данных это класс DbContext.
Entity Framework создала новый класс MyDatabase1Entities отнаследованный от класса DbContext
В файле "App.config" добавились строчки для соединения с Базой данных
<connectionStrings>
<add name="MyDatabase1Entities" connectionString="data source=EVGENI;initial catalog=MyDatabase1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>

Читать подробнее <connectionStrings> в .config файле...
Добавились файлы описывающие таблицы в Базе даных (то есть схема Базы данных):
Model1.Designer.cs
Model1.edmx.diagram
Model1.tt
Model1.Context.tt
  C#     Файл Book.cs
//---------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior
// in your application.
// Manual changes to this file will be overwritten if the code
// is regenerated.
// </auto-generated>
//---------------------------------------------

namespace ConsoleApplication2
{
     using System;
     using System.Collections.Generic;
    
     public partial class Book
     {
          public int Id { get; set; }
          public string Name { get; set; }
          public int Price { get; set; }
     }
}
  C#     Файл Model1.Context.cs
//----------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//----------------------------------------------------
namespace ConsoleApplication2
{
     using System;
     using System.Data.Entity;
     using System.Data.Entity.Infrastructure;
    
     public partial class MyDatabase1Entities : DbContext
     {
          public MyDatabase1Entities()
               : base("name=MyDatabase1Entities")
          {
          }
    
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
               throw new UnintentionalCodeFirstException();
          }
    
          public virtual DbSet<Book> Books { get; set; }
     }
}
Шаг 5. Пример "Загружаем данные из Базы данных используя C# код"
Добавим в файл Program.cs выделенные строчки
  C#     Файл Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
     class Program
     {
          static void Main(string[] args)
          {
               using (MyDatabase1Entities db = new MyDatabase1Entities())
               {
                    foreach (Book book in db.Books)
                         Console.WriteLine(book.Id + " " + book.Name + " " + book.Price);
               }
          }
     }
}
На заметку!
класс Book содержится в сгенерированном файле Book.cs
класс MyDatabase1Entities содержится в сгенерированном файле Model1.Context.cs
Результат примера
Шаг 6. Вывод
Подход Database First похож с Auto Code First.
В подходе Database First
создаются файлы:
В подходе Auto Code First
создаются файлы:
Book.cs
Model1.Context.cs
• В файле App.config добавились строчки для соединения с Базой данных

Добавились файлы модели (схемы) Базы даных:
• Model1.Context.tt
• Model1.Designer.cs
• Model1.edmx.diagram
• Model1.tt
Book.cs
Model1.cs
• В файле App.config добавились строчки для соединения с Базой данных
Я бы посоветовал для готовой Базы данных использовать Auto CodeFirst, и не использовать Database First.
Так как Database First добавляет лишние файлы (схему Базы данных).
А также при наличии изменений в Базе данных, измнения в C# файле проще вносить при подходе Auto CodeFirst
 
← Previous topic
Auto Code First. Entity Framework creates a C# class from an existing table in the → database
 
Next topic →
Model First. We create a model in Visual Studio. Using the Entity Framework model, → creates C# classes and a Database
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
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