dir.by  
  Поиск  
Компьютер, программы
Entity Framework (EF5, EF6) for working with a C database#
 Внешний ключ (Foreign Key) и каскадное удаление 
посмотрели 10265 раз
обновлено: 15 January 2019
Внешний ключ (Foreign Key) это связь с другой таблицей.

Чтобы образовать внешний ключ нужно чтобы
Имя_свойства_в_нашем_классе
=
Имя_класса_связанной_таблицы + Имя_ключа_из_связанной_таблицы

Каскадное удаление
• Если внешний ключ определяется как int? то внешний ключ может иметь null значения и нет каскадного удаления.
• Если внешний ключ определяется как int то внешний ключ не может иметь null значения и будет каскадное удаление.
Пример1 (foreign key может быть null)
  C#  
public class UserContext : DbContext
{
     // MyConnection1 это соединение с базой данных описанное в файле web.config
     public UserContext() : base("MyConnection1")
     {
     }

     public DbSet<User> Users {get; set;}
     public DbSet<Task> Tasks { get; set; }
}

public class User
{
     public int Id {get;set;}
     public string Email {get; set;}
     public string Password{get; set;}
}

public class Task
{
     public int Id { get; set; }
     public int Price { get; set; }

     public int? UserId { get; set; } // определяем внешний ключ (int? значит может иметь null значение)
     public User User { get; set; } // это тоже необходимо для внешнего ключа
}
На заметку!
Если внешний ключ определяется как int? то внешний ключ может иметь null значения и нет каскадного удаления.
В MS Sql Server база данных выглядит так:
Пример2 (foreign key не может быть null)
  C#  
public class UserContext : DbContext
{
     // MyConnection1 это соединение с базой данных описанное в файле web.config
     public UserContext() : base("MyConnection1")
     {
     }

     public DbSet<User> Users {get; set;}
     public DbSet<Task> Tasks { get; set; }
}

public class User
{
     public int Id {get;set;}
     public string Email {get; set;}
     public string Password{get; set;}
}

public class Task
{
     public int Id { get; set; }
     public int Price { get; set; }

     public int UserId { get; set; } // определяем внешний ключ (int значит НЕ может иметь null значение)
     public User User { get; set; } // это тоже необходимо для внешнего ключа
}
На заметку!
Если внешний ключ определяется как int то внешний ключ НЕ может иметь null значения и будет каскадное удаление.
В MS Sql Server база данных выглядит так:
 
← Previous topic
Entity Framework Type Conversion, Table Naming Conventions
 
Next topic →
DateTime & Date & Time Only in the Entity Framework
 
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