EF Code-First - Tạo Context và lớp thực thể từ database

Tạo Context và lớp thực thể từ database trong Code First

Ở phần này, bạn sẽ tìm hiểu cách tạo Context và các lớp thực thể từ cơ sở dữ liệu có sẵn, sử dụng phương pháp tiếp cận Code First.

Entity Framework cung cấp một cách đơn giản để sử dụng Code First cho cơ sở dữ liệu có sẵn. Nó sẽ tạo các lớp thực thể cho tất cả các bảng và view trong cơ sở dữ liệu hiện tại của bạn và cấu hình chúng với các attribute chú thích dữ liệu và Fluent API.

Để sử dụng Code First cho cơ sở dữ liệu có sẵn, nhấp chuột phải vào dự án của bạn trong Visual Studio -> Add -> New Item..

code first for an existing database

Chọn ADO.NET Entity Data Model trong hộp thoại Add New Item và đặt tên cho mô hình (đây sẽ là tên lớp Context) rồi nhấp vào nút Add.

code first for an existing database

Điều này sẽ mở trình hướng dẫn Entity Data Model như dưới đây. Chọn Code First from database và nhấn Next.

code first for an existing database

Chọn ADO.NET Entity Data Model trong hộp thoại Add New Item và đặt tên cho mô hình (đây sẽ là tên lớp Context) rồi nhấp vào nút Add.

code first for an existing database

Bây giờ, chọn các bảng và view mà bạn muốn tạo các lớp thực thể và nhấp vào Finish.

code first for an existing database

Điều này sẽ tạo ra tất cả các lớp thực thể cho các bảng và view trong cơ sở dữ liệu của bạn như được hiển thị bên dưới.

code first for an existing database

Nó cũng sẽ tạo lớp Context sau sử dụng Fluent API để cấu hình các lớp thực thể theo cơ sở dữ liệu của bạn.

namespace EFDemo
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;

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

        public virtual DbSet<Course> Courses { get; set; }
        public virtual DbSet<Standard> Standards { get; set; }
        public virtual DbSet<Student> Students { get; set; }
        public virtual DbSet<StudentAddress> StudentAddresses { get; set; }
        public virtual DbSet<Teacher> Teachers { get; set; }
        public virtual DbSet<View_StudentCourse> View_StudentCourse { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Course>()
                .Property(e => e.CourseName)
                .IsUnicode(false);

            modelBuilder.Entity<Course>()
                .HasMany(e => e.Students)
                .WithMany(e => e.Courses)
                .Map(m => m.ToTable("StudentCourse").MapLeftKey("CourseId").MapRightKey("StudentId"));

            modelBuilder.Entity<Standard>()
                .Property(e => e.StandardName)
                .IsUnicode(false);

            modelBuilder.Entity<Standard>()
                .Property(e => e.Description)
                .IsUnicode(false);

            modelBuilder.Entity<Standard>()
                .HasMany(e => e.Students)
                .WithOptional(e => e.Standard)
                .WillCascadeOnDelete();

            modelBuilder.Entity<Standard>()
                .HasMany(e => e.Teachers)
                .WithOptional(e => e.Standard)
                .WillCascadeOnDelete();

            modelBuilder.Entity<Student>()
                .Property(e => e.StudentName)
                .IsUnicode(false);

            modelBuilder.Entity<Student>()
                .Property(e => e.RowVersion)
                .IsFixedLength();

            modelBuilder.Entity<Student>()
                .HasOptional(e => e.StudentAddress)
                .WithRequired(e => e.Student)
                .WillCascadeOnDelete();

            modelBuilder.Entity<StudentAddress>()
                .Property(e => e.Address1)
                .IsUnicode(false);

            modelBuilder.Entity<StudentAddress>()
                .Property(e => e.Address2)
                .IsUnicode(false);

            modelBuilder.Entity<StudentAddress>()
                .Property(e => e.City)
                .IsUnicode(false);

            modelBuilder.Entity<StudentAddress>()
                .Property(e => e.State)
                .IsUnicode(false);

            modelBuilder.Entity<Teacher>()
                .Property(e => e.TeacherName)
                .IsUnicode(false);

            modelBuilder.Entity<Teacher>()
                .HasMany(e => e.Courses)
                .WithOptional(e => e.Teacher)
                .WillCascadeOnDelete();

            modelBuilder.Entity<View_StudentCourse>()
                .Property(e => e.StudentName)
                .IsUnicode(false);

            modelBuilder.Entity<View_StudentCourse>()
                .Property(e => e.CourseName)
                .IsUnicode(false);
        }
    }
}