dir.by  
  Поиск  
Компьютер, программы
Entity Framework (EF5, EF6) for working with a C database#
 Auto Code First. Entity Framework из существующей таблицы в базе данных → создает C# класс 
посмотрели 9191 раз
обновлено: 28 June 2018
Вручную создавать C# классы по готовым таблицам в Базе данных довольно трудно.
В этом случае мы можем использовать Auto Code First (Code First утилиту).
Эта Code First утилита есть в Visual Studio 2013, Visual Studio 2015, Visual Studio 2017...
План (3 шага)
Шаг 1. Создаем новое консольное приложение
Шаг 2. Создаем таблицу в Базе данных
Шаг 3. Code First утилита (ADO.NET Entity Data Model)
Нажимаем правой клавишей мыши на нашем приложении ConsoleApplication1
Выбираем AddNew ItemADO.NET Entity Data ModelCode First from database
Выбираем базу данных
На заметку! Галочка Save Connection settings in App.Config означает что в файле App.Config добавится строка соединения с Базой Данных.
Строка соединения будет иметь имя Model1.
На следующем шаге выбираем по каким таблицам будут создаваться C# классы
Нажимаем кнопку "Finish" и увидим что создались новые файлы с C# классами
Создался новый файл "Book.cs"
Entity Framework утилита создала новый класс Book для получения значений из Базы данных
Создался новый файл "Model1.cs"
Для подключения и работой с Базой данных нам нужен контекст данных это класс DbContext.
Entity Framework утилита создала новый класс Model1 отнаследованный от класса DbContext
В файле "App.config" добавились строчки для соединения с Базой данных
<connectionStrings>
<add name="Model1" connectionString="data source=EVGENI;initial catalog=MyDatabase1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>

Читать подробнее <connectionStrings> в .config файле...
  C#     Файл "Book.cs"
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;

[Table("Book")]
public partial class Book
{
public int Id { get; set; }

public string Name { get; set; }

public int Price { get; set; }
}
}
  C#     Файл "Model1.cs"
namespace ConsoleApplication1
{
     using System;
     using System.Data.Entity;
     using System.ComponentModel.DataAnnotations.Schema;
     using System.Linq;

     public partial class Model1 : DbContext
     {
          public Model1()
               : base("name=Model1")
          {
          }

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

          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
          }
     }
}
 
← Previous topic
Code First. We"re writing a C# class. Entity Framework uses our C# class → to create and populate a table in the database
 
Next topic →
Database First. Entity Framework creates a C# class from an existing table in the → 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