c# entity framework core树状结构增删改查

2021-03-11 08:31

阅读:344

标签:done   console   sep   new   efault   created   active   tip   ring   

首先创建一个.net core控制台程序,添加实体类

实体类:Employee

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace TreeEntityDemo
{
    /// 
    /// 员工实体
    /// 
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [ForeignKey(nameof(ManagerId))]
        public int? ManagerId { get; set; }
        public virtual Employee Manager { get; set; }
        public virtual ICollection Employees { get; set; }
    }
}

定义DbContext

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace TreeEntityDemo
{
    public class AppDbContext:DbContext
    {
        public AppDbContext()
        {

        }
        public AppDbContext(DbContextOptions options):base(options)
        {

        }
        public DbSet Employees { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity()
                .HasMany(x => x.Employees)
                .WithOne(x => x.Manager)
                .HasForeignKey(x => x.ManagerId)
                .OnDelete(DeleteBehavior.ClientSetNull);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
            var config = builder.Build();
            optionsBuilder.UseSqlServer(config.GetConnectionString("TreeDemoDb"));

        }
    }
}

配置数据库链接:appsettings.json

{
  "ConnectionStrings": {
    "TreeDemoDb": "Server=(localdb)\\MSSQLLocalDB;Database=TreeDemoDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

添加数据库迁移 Add-Migration

add-migration InitialCreate

在Program.cs中测试

using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace TreeEntityDemo
{
   class Program
   {
       static void Main(string[] args)
       {
           using (var context = new AppDbContext())
           {
               context.Database.EnsureCreated();
               if (!context.Employees.Any())
               {
                   context.Employees.AddRange(
                       new Employee()
                       {
                           Name = "Manager1"
                       },
                       new Employee()
                       {
                           Name = "Employee1"
                       },
                       new Employee()
                       {
                           Name = "Employee2"
                       },
                       new Employee()
                       {
                           Name = "Employee3"
                       }
                   );
               }
               context.SaveChanges();
           }
           //GetParent();
           SetParent();
           GetChildren();
           Console.WriteLine("Done!");
       }
      
       public static void Find()
       {
           using (var context = new AppDbContext())
           {
               var employees = context.Employees.FirstOrDefault(t => t.Name == "Employee1");
               Console.WriteLine(employees.Name);
               Console.WriteLine(employees.Manager.Name);
           }
       }

       /// 
       /// 删除所有
       /// 
       static void RemoveAll()
       {
           using (var context = new AppDbContext())
           {
               var employees = context.Employees
                   .Where(t => !string.IsNullOrEmpty(t.Name));
               context.RemoveRange(employees);
               context.SaveChanges();
           }
       }

       /// 
       /// 获取父类
       /// 
       static void SetParent()
       {
           using (var context = new AppDbContext())
           {
               var employee1 = context.Employees.FirstOrDefault(t => t.Name == "Employee1");
               var employee2 = context.Employees.FirstOrDefault(t => t.Name == "Employee2");
               var employee3 = context.Employees.FirstOrDefault(t => t.Name == "Employee3");
               var manager1 = context.Employees.FirstOrDefault(t => t.Name == "Manager1");
               employee1.Manager = manager1;
               employee2.Manager = manager1;
               employee3.Manager = manager1;
               context.Update(employee1);
               context.Update(employee2);
               context.Update(employee3);
               context.SaveChanges();
           }
       }

       /// 
       /// 获取子类
       /// 
       static void GetParent()
       {
           using (var context = new AppDbContext())
           {
               var employee1 = context.Employees.Include(t=>t.Manager).FirstOrDefault(t => t.Name == "Employee1");
               if (employee1.Manager==null)
               {
                   Console.WriteLine("null");
               }
               else
               {
                   Console.WriteLine(employee1.Manager.Name);
               }
           }
       }

       static void GetChildren()
       {
           using (var context = new AppDbContext())
           {
               var manager1 = context.Employees.FirstOrDefault(t => t.Name == "Manager1");
               var children = context.Employees.Where(t => t.ManagerId == manager1.Id);
               if (children!=null && children.Count()>0)
               {
                   foreach (var item in children)
                   {
                       Console.WriteLine(item.Name);
                   }
               }
               
           }
       }

       static void DeleteParent()
       {
           using (var context = new AppDbContext())
           {
               var manager1 = context.Employees.FirstOrDefault(t => t.Name == "Manager1");

               context.Employees.Remove(manager1);
               context.SaveChanges();
           }
       }

   }
}

c# entity framework core树状结构增删改查

标签:done   console   sep   new   efault   created   active   tip   ring   

原文地址:https://www.cnblogs.com/AlexanderZhao/p/12640506.html


评论


亲,登录后才可以留言!