码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2020-04-06 09:58:43      阅读:102      评论:0      收藏:0      [点我收藏+]

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

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

实体类:Employee

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

namespace TreeEntityDemo
{
    /// <summary>
    /// 员工实体
    /// </summary>
    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<Employee> 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<AppDbContext> options):base(options)
        {

        }
        public DbSet<Employee> Employees { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>()
                .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);
           }
       }

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

       /// <summary>
       /// 获取父类
       /// </summary>
       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();
           }
       }

       /// <summary>
       /// 获取子类
       /// </summary>
       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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!