EF Core一对多关系配置

  • 创建文章、评论实体类 ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace EFCoreRelation.Models { public class Article { public long ID { get; set; } public string Title { get; set; } public string Content { get; set; }

  1. public List<Comment> Comments { get; set; } = new List<Comment>();
  2. }

}

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace EFCoreRelation.Models { public class Comment { public long ID { get; set; }

  1. public string Message { get; set; }
  2. public Article Article { get; set; }
  3. }

}

  1. - 安装Nuget
  2. Microsoft.EntityFrameworkCore.SqlServer<br />Microsoft.EntityFrameworkCore.Tools
  3. - 创建配置类,实现一对多的外键配置,下面尤其要注意评论配置类。
  4. **多个评论有一篇文章(HasOne<Article>(c=>c.Article),一篇文章拥有多个评论(WithMany<Comment>(a=>a.Comments))**
  5. ```csharp
  6. using EFCoreRelation.Models;
  7. using Microsoft.EntityFrameworkCore;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace EFCoreRelation.Configs
  14. {
  15. public class ArticleConfig : IEntityTypeConfiguration<Article>
  16. {
  17. public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Article> builder)
  18. {
  19. builder.ToTable("T_Article");
  20. builder.Property(a => a.Content).IsRequired();
  21. builder.Property(a => a.Title).IsRequired().IsUnicode().HasMaxLength(255);
  22. }
  23. }
  24. }
  25. using EFCoreRelation.Models;
  26. using Microsoft.EntityFrameworkCore;
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Linq;
  30. using System.Text;
  31. using System.Threading.Tasks;
  32. namespace EFCoreRelation.Configs
  33. {
  34. public class CommentConfig : IEntityTypeConfiguration<Comment>
  35. {
  36. public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Comment> builder)
  37. {
  38. builder.ToTable("T_Comment");
  39. builder.Property(c => c.Message).IsRequired().IsUnicode();
  40. builder.HasOne<Article>(c => c.Article).WithMany(a => a.Comments).IsRequired();
  41. }
  42. }
  43. }
  • 创建AlbertDbContext ```csharp using EFCoreRelation.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

namespace EFCoreRelation.DbContexts { public class AlbertDbContext:DbContext { public DbSet

? Articles { get; set; } public DbSet? Comment { get; set; }

  1. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  2. {
  3. optionsBuilder.UseSqlServer(connectionString: "Server=.;Database=Albertefcore;" +
  4. "Trusted_Connection=True;MultipleActiveResultSets=true");
  5. }
  6. protected override void OnModelCreating(ModelBuilder modelBuilder)
  7. {
  8. base.OnModelCreating(modelBuilder);
  9. modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
  10. }
  11. }

}

  1. - 执行数据库迁移
  2. ```csharp
  3. Add-Migration "Init SQLServer"
  4. Update-Database
  • 查看数据库是否有数据(如果配置正常则已有数据)
  • 向数据库中插入值 ```csharp using EFCoreRelation.DbContexts; using EFCoreRelation.Models; using Microsoft.EntityFrameworkCore;

// 插入值 //Article article = new Article(); //article.Title = “微软.NET最新动态”; //article.Content = “微软发布了最新的.NET7 Preview版本,该版本优化了JWT配置”; //Comment comment1 = new Comment() { Message = “真的好棒” }; //Comment comment2 = new Comment() { Message = “终于优化了JWT了” }; //Comment comment3 = new Comment() { Message = “拥抱开源后微软变得很牛” }; //Comment comment4 = new Comment() { Message = “巨硬无敌” }; //article.Comments.Add(comment1); //article.Comments.Add(comment2); //article.Comments.Add(comment3); //article.Comments.Add(comment4); //using var ctx = new AlbertDbContext(); //ctx.Articles.Add(article); //await ctx.SaveChangesAsync();

// 移除全部数据 //using var ctx = new AlbertDbContext();

//foreach (var item in ctx.Articles) //{ // ctx.Articles.Remove(item); //} //ctx.SaveChanges();

// 注意SingleOrDefault返回空值的情况 using var ctx = new AlbertDbContext(); try { var articlesingle = ctx.Articles.Include(a => a.Comments).SingleOrDefault(c => c.ID == 4); foreach (var item in articlesingle.Comments) { Console.WriteLine(item.Message); }

} catch (Exception ex) { throw ex; }

```