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