EF-CodeFirst

Process About the Development of CodeFirst by using EF

CodeFirst

  1. we need to define the Model. These Model will be mapped to the DB.

Code Sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Models
{
    public class Course
    {
        public int CourseId { get; set; }
        public string Name { get; set; }
        public double Duration { get; set; }
        public string Description { get; set; }
        public Subject Subject { get; set; }
        public Tutor Tutor { get; set; }
        public ICollection<Enrollment> Enrollments { get; set; }
    }
    public class Enrollment
    {
        public int EnrollmentId { get; set; }
        public DateTime EnrollmentDate { get; set; }
        public Student Student { get; set; }
        public Course Course { get; set; }
    }
    public enum Gender
    {
        Male=0,
        Female=1
    }
    public class Student
    {
        public int StudentId { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Gender Gender { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public DateTime? RegistrationDate { get; set; }
        public DateTime? LastLoginDate { get; set; }
        public ICollection<Enrollment> Enrollments { get; set; }
    }
    public class Subject
    {
        public int SubjectId { get; set; }
        public string Name { get; set; }
        public ICollection<Course> Courses { get; set; }
    }
    public class Tutor
    {
        public int TutorId { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Gender Gender { get; set; }
        public ICollection<Course> Courses { get; set; }
    }    
}

  1. define the Model Mappers. Mapper including the rules to map the model to the DB Table, Column, Properties, Relationship.
    the nameSpace: Here, all the mapper class should inherit from
    the Template class EntityTypeConfiguration.

we can also refer to KeyWord FluentAPI, Tutorial

code Samples:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema;
using Models;
namespace DataAccess
{
    public class CourseMapper:EntityTypeConfiguration<Course>
    {
        public CourseMapper()
        {
            this.ToTable("Courses");
            this.HasKey(e => e.CourseId);
            this.Property(e => e.CourseId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();

            this.Property(e => e.Name).HasMaxLength(255).IsRequired();
            this.Property(e => e.Duration).IsRequired();
            this.Property(e => e.Description).HasMaxLength(1000).IsRequired();
            this.HasRequired(e => e.Subject).WithMany().Map(s => s.MapKey("SubjectId"));
            this.HasRequired(e => e.Tutor).WithMany().Map(s => s.MapKey("TutorId"));
        }
    }
    public class EnrollmentMapper:EntityTypeConfiguration<Enrollment>
    {
        public EnrollmentMapper()
        {
            this.ToTable("Enrollments");
            this.HasKey(e => e.EnrollmentId);
            this.Property(e => e.EnrollmentId).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(e => e.EnrollmentDate).IsRequired().HasColumnType("smalldatetime");

            this.HasOptional(e => e.Student).WithMany(e => e.Enrollments).Map(s => s.MapKey("StudentId")).WillCascadeOnDelete(false);
            this.HasOptional(e => e.Course).WithMany(c => c.Enrollments).Map(s => s.MapKey("CourseId")).WillCascadeOnDelete(false);

        }
    }
    public class StudentMapper:EntityTypeConfiguration<Student>
    {
        public StudentMapper()
        {
            this.ToTable("Students");
            this.HasKey(e => e.StudentId);
            this.Property(e => e.StudentId).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(e => e.Email).HasMaxLength(255).IsRequired().IsUnicode(false);
            this.Property(e => e.UserName).HasMaxLength(50).IsRequired().IsUnicode(false);
            this.Property(e => e.Password).HasMaxLength(255).IsRequired();
            this.Property(e => e.FirstName).IsRequired().HasMaxLength(50);
            this.Property(e => e.LastName).IsRequired().HasMaxLength(50);
            this.Property(e => e.Gender).IsOptional();
            this.Property(e => e.RegistrationDate).IsOptional().HasColumnType("smalldatetime");
            this.Property(e => e.LastLoginDate).IsOptional().HasColumnType("smalldatetime");
            this.Property(e => e.DateOfBirth).IsOptional().HasColumnType("smalldatetime");
        }
    }
    public class SubjectMapper:EntityTypeConfiguration<Subject>
    {
        public SubjectMapper()
        {
            this.ToTable("Subjects");
            this.HasKey(e=>e.SubjectId);
            this.Property(e => e.SubjectId).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(e => e.Name).IsRequired().HasMaxLength(255);
        }
    }
    public class TutorMapper:EntityTypeConfiguration<Tutor>
    {
        public TutorMapper()
        {
            this.ToTable("Tutors");
            this.HasKey(e => e.TutorId);
            this.Property(e => e.TutorId).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(e => e.UserName).IsRequired().HasMaxLength(50);
            this.Property(e => e.FirstName).IsRequired().HasMaxLength(50);
            this.Property(e => e.LastName).IsRequired().HasMaxLength(50);
            this.Property(e => e.Email).IsRequired().HasMaxLength(50).IsUnicode(false);
            this.Property(e => e.Password).IsRequired().HasMaxLength(255).IsUnicode(false);
            this.Property(e => e.Gender).IsOptional();
        }
    }
}

  1. The last thing we need is DbContext, we need to define a class inherited from it. These elemments are necessary: Constructor, DbSet Model, protected override void OnModelCreating(DbModelBuilder modelBuilder),
    For reference Here.

Firstly, Constructor, string parameter represent the name in webconfig or config about connectionstring, or just the connection string with format ConnectionString="".
if nothing prvided, it will create a Tempe DB, in the user folder.

Secondly, DbSet Ts, by conversion, we use the T class with subfix 's' to represent Table.

Thirdly, About the Database.SetInitializer, MSDN, we need to provide
the class inheriting the interface IDatabaseInitializer.
Generally, we have three implementions: DropCreateDatabaseIfModelChanges, DropCreateDatabaseAlways, CreateDatabaseIfNotExists.
For Database migration we can use MigrateDatabaseToLatestVersion
For the method DbMigrationsConfiguration.Seed, we can refer it here.
Generally to say, only MigrateDatabaseToLatestVersion is used, this method will be called after upgrading to the latest migration.
migration will be called only when the db is not existing or the db model is not mathing the model defined in our code.

Code Sample:

#define Debug
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity;
using Models;
using System.Data.Entity.Migrations;
namespace DataAccess
{
    public class DataContext:DbContext
    {
        public DataContext():base("TestDb")
        {
            Configuration.LazyLoadingEnabled = false;
            Configuration.ProxyCreationEnabled = false;
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext,DataContextMigrationConfiguration>());
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }
        public DbSet<Tutor> Tutors { get; set; }
        public DbSet<Subject> Subjects { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new StudentMapper());
            modelBuilder.Configurations.Add(new EnrollmentMapper());
            modelBuilder.Configurations.Add(new TutorMapper());
            modelBuilder.Configurations.Add(new SubjectMapper());
            modelBuilder.Configurations.Add(new CourseMapper());
            base.OnModelCreating(modelBuilder);
        }
    }
    public class DataContextMigrationConfiguration:DbMigrationsConfiguration<DataContext>
    {
        public DataContextMigrationConfiguration()
        {
            this.AutomaticMigrationDataLossAllowed = true;
            this.AutomaticMigrationsEnabled = true;
        }
#if Debug
        protected override void Seed(DataContext context)
        {
            new LearningDataSeeder(context).Seed();
        }
#endif
    }   
     
}

posted @ 2016-08-31 17:45  kongshu  阅读(386)  评论(0编辑  收藏  举报