dir.by  
Поиск >>

Компьютер, программы
→
Entity Framework (EF5, EF6) for working with a C database#
 Model First. Мы создаем модель в Visual Studio. По модели Entity Framework → создает C# классы и Базу данных 
посмотрели 12967 раз
обновлено: 4 July 2018
Суть данного подхода состоит в том, что мы делаем модель в Visual Studio.
Автоматически по модели создаются:
• C# классы
• База данных
План (6 шагов)
Шаг 1. Создаем новое консольное приложение
Шаг 2. Создаем модель (Empty EF Designer Model)
Нажимаем правой клавишей мыши на нашем приложении ConsoleApp1
Выбираем Add → New Item → ADO.NET Entity Data Model → Empty EF Designer Model
Нажимаем Finish
Появится пустое окно создания модели
Нажимаем в меню View -> Toolbox
Добавим Entity (сущность).
Нажимаем правой клавишей мыши на окне модели → Add New → Entity ...
Добавим свойства:
Name
Book
Чтобы добавить свойства нужно нажать правой клавишей мыши на окне Book → Add New → Scalar Property
Вот что получилось:
Scalar Property этот свойства на основе простейших типов int, float, string и т.д.
По умолчанию все добавляемые свойства имеют тип string.
Но мы можем изменить тип в окне свойств.

Поставим для свойства Price тип Int32
Для этого нажмем правой клавишей мыши на Price -> Properties
Шаг 3. Сгенерируем C# код по модели
Нажмем правой клавишей мыши на окне модели -> Add Code Generation Item ...
После этого в проекте Model1.edmx мы увидим
• Model1.Context.tt которая содержит файл Model1.Context.cs
• Model1.tt которая содержит файл Book.cs
  C#     Файл Book.cs
//----------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected ...
// Manual changes to this file will be overwritten ...
// </auto-generated>
//----------------------------

namespace ConsoleApp1
{
     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 ...
// Manual changes to this file will be overwritten ...
// </auto-generated>
//------------------------------------------------------------------------------

namespace ConsoleApp1
{
     using System;
     using System.Data.Entity;
     using System.Data.Entity.Infrastructure;
    
     public partial class Model1Container : DbContext
     {
          public Model1Container()
               : base("name=Model1Container")
          {
          }
    
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
               throw new UnintentionalCodeFirstException();
          }
    
          public virtual DbSet<Book> BookSet { get; set; }
     }
}
Шаг 4. Сгенерируем Базу данных по модели
Нажмем правой клавишей мыши на окне модели -> Generate Database from Model ...
Откроется окно для подключения к Базе данных.
Нажмем на кнопку "New Connection"
Выберем Microsoft SQL Server
Server name:
Server name это имя сервера базы данных.
Имя сервера базы данных появляется при открытии SQL Server Management Studio...
Я написал EVGENIMSSQLSERVER2012
Select or enter a database name:
Пишем новое название базы данных (или выбираем существующую Базу данных)
Я написал название MyDatabase1
Нажимаем OK
После этого будет сгенерирован скрипт базы данных:
Нажмем Finish (Готово).
Откроется файл скрипта User.edmx.sql.
  Файл Model1.edmx.sql
-- --------------------------------------------------
-- Entity Designer DDL Script for SQL Server 2005, 2008, 2012 and Azure
-- --------------------------------------------------
-- Date Created: 07/04/2018 11:24:50
-- Generated from EDMX file: D:\\ConsoleApp1\Model1.edmx
-- --------------------------------------------------

SET QUOTED_IDENTIFIER OFF;
GO
USE [MyDatabase1];
GO
IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]');
GO

-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints
-- --------------------------------------------------



-- --------------------------------------------------
-- Dropping existing tables
-- --------------------------------------------------



-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------


-- Creating table 'BookSet'
CREATE TABLE [dbo].[BookSet] (
[Id] int IDENTITY(1,1) NOT NULL,
[Name] nvarchar(max) NOT NULL,
[Price] int NOT NULL
);
GO

-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------


-- Creating primary key on [Id] in table 'BookSet'
ALTER TABLE [dbo].[BookSet]
ADD CONSTRAINT [PK_BookSet]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO

-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------

-- --------------------------------------------------
-- Script has ended
-- --------------------------------------------------
Нам надо будет запустить этот скрипт.
Для этого нажмем в верхнем левом углу на зеленую кнопку
Visual Studio нам покажет об успешном создании Базы данных.
Шаг 5. Проверяем как создалась наша База данных и таблица в Microsoft SQL Server
Note! You must have Microsoft SQL Server installed. If you don't have it, then need to download and install Microsoft SQL Server ...

Note! You must have SQL Server Management Studio installed. If you don't have it, then need to download and install SQL Server Management Studio ...

To open SQL Server Management Studio, we click on the icon on the desktop:
Old version SQL Server Management Studio (this is version 18)
New version SQL Server Management Studio (this is version 22)
 
A window will appear and press the "Connect" button:
 
Old version SQL Server Management Studio (this is version 18)
New version SQL Server Management Studio (this is version 22)
 
After 20 seconds, we will see that SQL Server Management Studio is loaded:
Old version SQL Server Management Studio (this is version 18)
New version SQL Server Management Studio (this is version 22)
Видим, что автоматически:
• создалась новая база данных MyDatabase1
• создалась новая таблица BookSet
Шаг 6. Пример "Загружаем данные из Базы данных используя C# код"
Добавим в файл Program.cs выделенные строчки
  C#  
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 (Model1Container db = new Model1Container())
               {
                    // Добавляем данные
                    db.BookSet.Add(new Book() { Name = "Граф Монтекристо", Price = 123 });
                    db.BookSet.Add(new Book() { Name = "Властелин колец", Price=267 });
                    db.BookSet.Add(new Book() { Name = "Три кота", Price = 125 });

                    // Сохраняем данные в Базу данных
                    db.SaveChanges();

                    // показываем данные из Базы Данных
                    foreach(Book book in db.BookSet)
                    {
                         Console.WriteLine(book.Id + " " + book.Name + " " + book.Price);
                    }
               }
          }
     }
}
Результат примера
 
← Previous topic
Database First. Entity Framework creates a C# class from an existing table in the → database
 
Next topic →
Iterating over data in the Entity Framework
 
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