Nuget:
Microsoft.AspNetCore.All
Microsoft.EntityFrameworkCore//Include 导航属性在此空间
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
微软懒加载文档:
https://docs.microsoft.com/en-us/ef/core/querying/related-data
注入EF:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDbContext<AppDbContext>(options => { //options.UseSqlServer(Configuration.GetConnectionString("SqlConnection")); options.UseSqlServer(Configuration["ConnectionStrings:SqlConnection"]); }); services.AddMvc() .AddJsonOptions( options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore );//设置禁止循环引用 var serviceProvider = services.BuildServiceProvider(); using (var context = serviceProvider.GetService<AppDbContext>()) { context.Database.Migrate(); } }
种子数据:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Teacher>().HasMany(x=>x.Students);//设置关系 modelBuilder.Entity<Teacher>().HasData(new List<Teacher>() { new Teacher() { age=3, id=1, name="T1"} ,new Teacher() { age=3, id=2, name="S2"} , new Teacher() { age=3, id=3, name="F3"} , new Teacher() { age=3, id=4, name="D4"} }); modelBuilder.Entity<Student>().HasOne(c=>c.Teacher);//设置关系 modelBuilder.Entity<Student>().HasData(new List<Student>() { new Student() { age=3, id=1, name="T" ,TeacherId=2} ,new Student() { age=3, id=2, name="S" ,TeacherId=2} , new Student() { age=3, id=3, name="F" ,TeacherId=1} , new Student() { age=3, id=4, name="D" ,TeacherId=3} }); base.OnModelCreating(modelBuilder); }
查询:
[HttpGet] public IEnumerable<object> Get() { AppDbContext db = new AppDbContext(); var student = db.Students.Include(x=>x.Teacher).Where(x=>x.id==1).ToList(); var t = db.Teachers.Include(x => x.Students).Where(x=>x.id==2); return t.ToList(); }
实体:
public class Student { public int id { get; set; } public int age { get; set; } public string name { get; set; } [ForeignKey("Teacher.Id")]//设置外键,表.主键 public int TeacherId { get; set; } //[JsonIgnore] 禁止序列化JSON public virtual Teacher Teacher { get; set; } //= new Teacher(); } public class Teacher { public int id { get; set; } public int age { get; set; } public string name { get; set; } //[JsonIgnore] 禁止序列化JSON public virtual ICollection<Student> Students { get; set; }// = new List<Student>(); }