Program.cs
Example C# 2018
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeFirst { class Program { static void Main(string[] args) { using (var db = new StudentContext()) { var student = new Student() { Name = "Antonio" }; var subject1 = new Subject() { Name = "Subject 1" }; var subject2 = new Subject() { Name = "Subject 2" }; student.SubjectsList.Add(subject1); student.SubjectsList.Add(subject2); db.Students.Add(student); db.SaveChanges(); } } } public class Student { public Student() { this.SubjectsList = new List<Subject>(); } public int StudentID { get; set; } public string Name { get; set; } public virtual List<Subject> SubjectsList { set; get; } } public class Subject { public int SubjectID { get; set; } public string Name { get; set; } public virtual Student Student { get; set; } } class StudentContext : DbContext { public DbSet<Student> Students { set; get; } public DbSet<Subject> Subjects { set; get; } } }
App.config
Example C# 2018
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="StudentContext" connectionString="Server=ANTONIO-PC\SQLEXPRESS; Database=StudentDatabase; User=sa; Password=1234567" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Output
Thêm Birthday vào bảng Student
Tool > Nuget Package Manager > Package Manage Console
// Chạy lệnh này tại cửa sổ Console
Enable-Migrations
Add-Migration AddBirthday
Update-Database
Output
Xóa Birthday trên bảng Student
Add-Migration RemoveBirthday
Update-Database
Output
0 nhận xét:
Post a Comment