EF6 代码优先,根据model类自动建表
EF代码优先
新建一个控制台应用程序,代码如下
控制台代码
private static void Main(string[] args)
{
//SchoolContext:EF6自动建表的类
using (var ctx = new SchoolContext())
{
//Student表名
var student = new Student() { StudentName = "Bill" };
//给Student表添加数据
ctx.Students.Add(student);
//给Teachers添加数据
ctx.Teachers.Add(new Teacher() { TeacherName="嫖老师",ModeOfTeaching= TeachingMode.ClassRoom });
//保存操作
ctx.SaveChanges();
//EF6查询动作,FirstOrDefault:取序列中满足条件的第一个元素,如果没有元素满足条件,则返回默认值
var dStu = ctx.Students.Where(x => x.StudentName == "Bill").FirstOrDefault();
//删除Students表查出来StudentName = "Bill"的数据
ctx.Students.Remove(dStu);
ctx.SaveChanges();
}
Console.WriteLine("Demo completed.");
Console.ReadLine();
}
这个是后台代码
//继承DbContext实现EF6的相关操作
public class SchoolContext : DbContext
{
//构造函数,base里写连接数据库语句
public SchoolContext() : base("Server=.;uid=sa;pwd=123456;database=EFTest;")
{
//数据库不存在时重新创建数据库,避免了新建完库后有再次重复该动作
Database.SetInitializer<SchoolContext>(new CreateDatabaseIfNotExists<SchoolContext>());//
//输出SQL日志
Database.Log += PrintSql;
}
public void PrintSql(string sql)
{
Console.WriteLine(sql);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Adds configurations for Student from separate class
//执行StudentConfigurations里的相关配置
modelBuilder.Configurations.Add(new StudentConfigurations());
//使Teacher这个model新建的表名为TeacherInfo
modelBuilder.Entity<Teacher>()
.ToTable("TeacherInfo");
modelBuilder.Entity<Teacher>()
.MapToStoredProcedures();
}
/// <summary>
/// 实例化后可以操作下边表的增删改查
/// </summary>
public DbSet<Student> Students { get; set; }
public DbSet<Grade> Grades { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Teacher> Teachers { get; set; }
public DbSet<StudentAddress> StudentAddresses { get; set; }
}
StudentConfigurations类的配置
public class StudentConfigurations : EntityTypeConfiguration<Student>
{
public StudentConfigurations()
{
this.Property(s => s.StudentName)
.IsRequired()
.HasMaxLength(50);
this.Property(s => s.StudentName)
.IsConcurrencyToken();
// Configure a one-to-one relationship between Student & StudentAddress
//StudentAddress类重写了被Student里的StudentAddress(Address)
//WithRequired后者包含前者一个不为null的实例
//https://www.cnblogs.com/suizhikuo/p/4742372.html
this.HasOptional(s => s.Address) // Mark Student.Address property optional (nullable)
.WithRequired(ad => ad.Student); // Mark StudentAddress.Student property as required (NotNull).
}
}
其中一个model-Student类
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime? DateOfBirth { get; set; }//?代表可以为空
public decimal Height { get; set; }
public float Weight { get; set; }
public byte[] RowVersion { get; set; }
//fully defined relationship
public int? GradeId { get; set; }
public virtual Grade Grade { get; set; }
public virtual StudentAddress Address { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
github源码下载
https://github.com/entityframeworktutorial/EF6-Code-First-Demo
EF增删改的操作
https://www.cnblogs.com/hao-1234-1234/archive/2018/04/09/8760985.html
EF 通过DataAnnotations配置属性和类型
https://www.cnblogs.com/GreenLeaves/p/7589350.html
EF 如何关闭自动检测_MigrationHistory
https://blog.csdn.net/weixin_30660027/article/details/97224729
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!