EF-CodeFirst
Process About the Development of CodeFirst by using EF
CodeFirst
- 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; }
}
}
- 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();
}
}
}
- 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
Thirdly, About the Database.SetInitializer
, MSDN, we need to provide
the class inheriting the interface IDatabaseInitializer
Generally, we have three implementions: DropCreateDatabaseIfModelChanges
For Database migration we can use MigrateDatabaseToLatestVersion
For the method DbMigrationsConfiguration
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
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构