导航属性是作为.NET ORM核心功能中的核心,在SqlSugar没有支持导航属性前,都说只是一个高级DbHelper, 经过3年的SqlSugar重构已经拥有了一套
非常成熟的导航属性体系,本文不是重点讲SqlSugar而是重点讲导航属性的作用,让更多写Sql人还未使用ORM的人了解到ORM的作用。
用户根据权限过滤,用户根据组织过滤 等这种多对多情况用SQL就相当复杂 ,例如:用SQL写一个多对多过滤就要联3个表(主表 中间表 从表),如果
Where中用到多个多对多或者嵌套多对多那写SQL简直就是恶梦 (一对多和一对一也有提升,没有多对多明显)
//EF CORE查询
var Persons= dbContext.Person //需要定义DbSet才能点出来
.Where(it=>it.Files.Any(y=>y.ChildFiles.Any(s=>s.name=="A"))).ToList()
//SqlSugar 查询
var Persons= dbContext.Queryable<Person>()
.Where(it=>it.Files.Any(y=>y.ChildFiles.Any(s=>s.name=="A"))).ToList()
用SQL写如下:
SELECT p.*
FROM Person p
WHERE EXISTS (
SELECT 1
FROM PersonFile pf
INNER JOIN File f ON pf.FileId = f.FileId
INNER JOIN PersonFile pf2 ON f.FileId = pf2.FileId
WHERE pf.PersonId = p.PersonId
AND pf2.PersonId IN (
SELECT p2.PersonId
FROM Person p2
INNER JOIN PersonFile pf3 ON p2.PersonId = pf3.PersonId
INNER JOIN File f2 ON pf3.FileId = f2.FileId
WHERE f2.name = 'A'
)
)
像SAAS系统这种多对多用的非常多,特别在组织、用户、角色、文件等无处理不在,这也是为什么要用ORM的原因
如果您的人事管理需要包含更多的信息,例如学历和工作经验等字段,您可以在代码中添加相应的实体和关联。
假设您有以下实体:人员(Person)、部门(Department)、职位(Position)、学历(Education)和工作经验(WorkExperience)。
var person = new Person
{
// 设置人员属性...
Department = new Department
{
// 设置部门属性...
},
Position = new Position
{
// 设置职位属性...
},
Education = new Education
{
// 设置教育属性...
},
WorkExperience = new WorkExperience
{
// 设置工作经历属性...
}
};
代码如下:
//SqlSugar 导航插入
db.InsertNav(person)
.Include(z1 => z1.Department)
.Include(z1 => z1.Position)
.Include(z1 => z1.Education)
.Include(z1 => z1.WorkExperience)
.ExecuteCommand();//导航插入 一句就能搞定,先插入主表,然后在根据主表的主键在插入从表,特别是自增列用导航代码清爽很多
因为Sql本身就不支持对多层级结构查询,所以不用ORM想实现高性能的多层级结构是需要花大量精力去优化和写代码的
//EF CORE查询
var Persons= dbContext.Person
.Include(z1 => z1.Department)
.Include(z1 => z1.Position)
.Include(z1 => z1.Education)
.Include(z1 => z1.WorkExperience).ToList()
EF多对多
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
// 其他学生属性...
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
// 其他课程属性...
public virtual ICollection<Student> Students { get; set; }
}
public class StudentCourse
{
public int CourseId { get; set; }
public int StudentId { get; set; }
}
// 配置多对多关系
protected override void OnModelCreating(ModelBuilder modelBuilder)
{ modelBuilder.Entity<Student>()
.HasMany(s => s.Courses)
.WithMany(c => c.Students) .UsingEntity(j => j.ToTable("StudentCourse"));
}
EF一对多和一对一
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
// 其他部门属性...
public virtual ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
// 其他员工属性...
public int DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
// 配置一对多关系
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Department>()
.HasMany(d => d.Employees)
.WithOne(e => e.Department)
.HasForeignKey(e => e.DepartmentId);
}
SqlSugar多对多
//实体
public class ABMapping1
{
[SugarColumn(IsPrimaryKey = true)]//中间表可以不是主键
public int AId { get; set; }
[SugarColumn(IsPrimaryKey = true)]//中间表可以不是主键
public int BId { get; set; }
}
public class A1
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
[Navigate(typeof(ABMapping1), nameof(ABMapping1.AId), nameof(ABMapping1.BId))]//注意顺序
public List<B1> BList { get; set; }//只能是null不能赋默认值
}
public class B1
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
[Navigat(typeof(ABMapping1), nameof(ABMapping1.BId), nameof(ABMapping1.AId))]//注意顺序
public List<A1> AList { get; set; }//只能是null不能赋默认值
}
Sqlugar一对一和一对多
//实体
public class StudentA
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int StudentId { get; set; }
public string Name { get; set; }public int SchoolId { get; set; }
[Navigate(NavigateType.OneToOne, nameof(SchoolId))]//一对一 SchoolId是StudentA类里面的
public SchoolA SchoolA { get; set; } //不能赋值只能是null
}
public class SchoolA
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id{ get; set; }
public string SchoolName { get; set; }
[Navigate(NavigateType.OneToMany, nameof(BookA.studenId))]//一对多 BookA表中的studenId
public List<BookA> Books { get; set; }//注意禁止给books手动赋值
}
var list3 = db.Queryable<UnitaStudentA>()
.IncludesAllFirstLayer().ToList();//有重载可以排除不想要的
//排除说明:
//IncludesAllFirstLayer(nameof(UnitaStudentA.ProjectPhases))
//这样就是排除ProjectPhases的导航属性
//可以排除多个
//IncludesAllFirstLayer("a","b")
//自动导航如果有重复的情况: 谁在前面执行哪个
var list3 = db.Queryable<UnitaStudentA>()
.Includes(it=>it.Order.Where(s=>s.id==1).ToList())
.IncludesAllFirstLayer().ToList();//自动导航和Order重复
//根据名字导航
db.Queryable<Order>()
//等同于Includes(it=>it.ProjectPhases)
.IncludesByNameString(nameof(Order.ProjectPhases)).ToList()
//自动写法,Books下面的A和B都会查询出来
.IncludesAllSecondLayer(x=>x.Books) //自动只能有这么多层次,更深层级需要手动写法
//手动写法
.Includes(x => x.Books,x=>x.A)
.Includes(x => x.Books,x=>x.B)
在前二年SqlSugar导航只能说够用,并不算好用,今年重点将导航DTO进行了强化
//简单的用法 5.1.4.71
var list = db.Queryable<Student_004>()
.Includes(x => x.books)
.Select(x => new Student_004DTO
{
books = x.books
}, true)//true是自动映射其他属性,匿名对象需要手动
.ToList();
//Mapster转换 5.1.4.71
var list = db.Queryable<Student_004>()
.Includes(x => x.books)
.Select(x => new Student_004DTO
{
name=x.Name,
books = x.books.Adapt<List<BooksDTO>>() //导航对象用 Mapster转换 (NUGET安装)
})
.ToList();
//DTO中用方法 5.1.4.71
var list = db.Queryable<Student_004>()
.Includes(x => x.books)
.Select(x => new Student_004DTO
{
name=x.Name,
//可以是C#任何方法结尾
bookIds=x.books.Select(it=>it.id).ToList()
})
.ToList();
//联表查询用DTO写法 5.1.4.71
var list5= db.Queryable<Student_004>()
.Includes(x => x.school_001, x => x.rooms)
.Includes(x => x.books)
.LeftJoin<Order>((x, y) => x.Id==y.sid)
.Select((x,y) => new Student_004DTO
{
SchoolId = x.SchoolId,
books = x.books,
school_001 = x.school_001,
Name=y.Name
})
.ToList();
当你遇到繁琐的数据库操作时,.NET SQLSugar就像是一双温暖的手,帮你轻松解决难题。它是一个强大的工具,让你的数据库管理变得更简单、更高效。下载.NET SQLSugar吧,让它成为你的数据之路上的得力助手,让你的编程之旅充满感动与喜悦!
原码下载: https://github.com/DotNetNext/SqlSugar
.NET中无论是EF CORE还是SQLSUGAR 使用了导航属性都不再需要费心写繁琐的SQL语句,只需简单地调用导航属性,便能轻松获取所需的数据。让我们一起追随这份感动,选择使用导航属性,让编程的旅途更加愉悦,让代码的世界充满美好与便捷!