一、建立文章、评论类

 /// <summary>
    /// 文章
    /// </summary>
  public  class Artitle
    {
        public  int Id { get; set; }
        public  string Ttile { get; set; }
        public string Content { get; set; }

        public List<Comment> Comments = new List<Comment>();//评论
    }
/// <summary>
    /// 评论
    /// </summary>
   public  class Comment
    {
        public int Id { get; set; }
        public string Message { get; set; }
//每个评论都有对应的文章
public Artitle theArtitle { get; set; } }

二、创建数据库操作类及对应的建表映射关系类

 /// <summary>
    /// 文章映射关系类
    /// </summary>
    class ArtitleMaps : IEntityTypeConfiguration<Artitle>
    {
        public void Configure(EntityTypeBuilder<Artitle> builder)
        {
            builder.ToTable("artitle");
            builder.Property(b => b.Id).IsUnicode().ValueGeneratedOnAdd();
            builder.Property(b => b.Ttile).IsRequired().HasMaxLength(50);
            builder.Property(b => b.Content).IsRequired().HasMaxLength(50);
        }
    }

此时一对多的关系我们在Comment映射类中指定(同样也可以在Artitle指定)

    /// <summary>
    /// 评论映射关系类
    /// </summary>
   public class CommentMap:IEntityTypeConfiguration<Comment>
    {

        public void Configure(EntityTypeBuilder<Comment> builder)
        {
            builder.ToTable("comment");
            builder.Property(b => b.Id).IsUnicode().ValueGeneratedOnAdd();
            builder.Property(b => b.Message).IsRequired().HasMaxLength(50);
            //指定一个外键theArtitle,artitle包含多个Comments
            builder.HasOne<Artitle>(a=>a.theArtitle).WithMany(c=>c.Comments).IsRequired();
        }
    }

如果在Article里指定

 

 

DBContext工具类(我们引用的是开源的 Pomelo.EntityFrameworkCore;UseMySql,和EFCore Study(1)里引用自带MYSql类库的不同)

    /// <summary>
    /// 论坛DBContext
    /// </summary>
   public  class ForumDBContext:DbContext
    {
        public DbSet<Artitle> artitles { get; set; }
        public DbSet<Comment> comments { get; set; }
        private const string ConnectionString = "server=127.0.0.1;port=3306;database=efcorestudy;uid=root;pwd=root;";
        
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            //我们引用的是开源的 Pomelo.EntityFrameworkCore;UseMySql方法有所不同
            optionsBuilder.UseMySql(ConnectionString, new MySqlServerVersion(new Version(8, 0, 23)));
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
        }
       
    }

三、数据生成

还是选择工具-->NuGet包管理器--->程序包管理器控制台--->输入命令:Add-Migration init -->执行完后再输入命令: Update-Database

生成情况:

Artitle:

 

Comment:

 

 

 生成外键theAritleId

 

 

 四、级联操作

在Program.cs里

class Program
{
  static void Main(string[] args)
  {

     using (var context = new ForumDBContext())
     {

        //操作代码

     }

  }
}

#关系插入

Artitle ac = new Artitle() { Ttile = "俄罗斯在日本领域发射导弹", Content = "2021年10月21日俄罗斯占领日本领域。。。。。。" };
                Comment c1 = new Comment() { Message = "太刚了" };
                Comment c2 = new Comment() { Message = "不愧是战斗民族" };
                //通过实体类指定一对多关系
                ac.Comments.Add(c1);
                ac.Comments.Add(c2);

                //只需要将“一”插入数据库,“一”对应的“多”因为已经在实体类里指定,也会被EFCore一同插入
                context.artitles.Add(ac);
                context.SaveChanges();

 

#关系查找——“一”到多

 //关联查询-
                //Include(a=>a.Comments)查询包含评论Comments
                //artitle的Id == 1
                var artitle = context.artitles.Include(a=>a.Comments).Single<Artitle>(ar => ar.Id == 1);
                Console.WriteLine(artitle.Id+","+artitle.Ttile);
                foreach (var item in artitle.Comments)
                {
                    Console.WriteLine(item.Id+","+item.Message);
                }

 

 //查看执行的sql:

var artitle = context.artitles.Include(a => a.Comments).Single<Artitle>(ar => ar.Id == 1);
                IQueryable<Artitle> list = context.artitles.Include(a => a.Comments).Where(ar => ar.Id == 1);
                var query = list.ToQueryString();
                Console.WriteLine("query:"+query);

 

#关系查找——多到“一”

//关联查询——从多到一
                //查出Id == 1的评论及评论对应的文章
                var comment = context.comments.Include(c => c.theArtitle).Single<Comment>(c => c.Id == 1);
                Console.WriteLine("评论:" + comment.Message);
                Console.WriteLine("评论对应文章:" + comment.theArtitle.Ttile);

 

 

 

//查看执行的sql

IQueryable<Comment> list =  context.comments.Include(c => c.theArtitle);
                var query = list.ToQueryString();
                Console.WriteLine("query:" + query);