c# - 如何在 linq2Db 中加载子集合?
问题描述
我在我的 sql 中创建了下表。
create table Department
(
Id uniqueidentifier primary key not null,
Name nvarchar(255),
IsActive bit
)
create table Employee
(
Id uniqueidentifier primary key not null,
Name nvarchar(255),
Age int,
Address nvarchar(255),
Email varchar(max),
Dob datetime,
DeptId uniqueidentifier,
IsActive bit,
Foreign key (DeptId) references Department(Id)
)
在员工表中,“DeptId”是外键。我已经编写了代码来获取其部门的所有员工。
这里的问题是我让员工的部门为空。
我记得在使用 EF core 时,我做了这样的事情:
var employees = db.Employees.Include(e => e.Department);
上面的代码返回带有部门的员工,但是在使用 linq2Db 时,如何编写代码来获取部门的员工?
这是我的代码:
Employee.cs
public class Employee
{
[PrimaryKey]
public Guid Id { get; set; }
public string Name { get; set; }
public int? Age { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public DateTime? Dob { get; set; }
public Guid? DeptId { get; set; }
public bool? IsActive { get; set; }
public virtual Department Department { get; set; }
}
部门.cs
public class Department
{
public Department()
{
this.Employees = new HashSet<Employee>();
}
[PrimaryKey]
public System.Guid Id { get; set; }
public string Name { get; set; }
public bool? IsActive { get; set; }
[Association(ThisKey = nameof(Department.Id), OtherKey = nameof(Employee.DeptId))]
public virtual ICollection<Employee> Employees { get; set; }
}
SampleDbContext.cs
public class SampleDbContext : DataConnection
{
public SampleDbContext(LinqToDbConnectionOptions<SampleDbContext> options)
: base(options)
{
}
public ITable<Employee> Employees => GetTable<Employee>();
public ITable<Department> Departments => GetTable<Department>();
}
员工控制器.cs
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly SampleDbContext _sampleDbContext;
public EmployeeController(SampleDbContext sampleDbContext)
{
_sampleDbContext = sampleDbContext;
}
// GET: api/<EmployeeController>
[HttpGet]
public async Task<Employee[]> Get()
{
return await _sampleDbContext.Employees.ToArrayAsync();
}
}
有人可以帮我吗?
谢谢 !!
解决方案
推荐阅读
- javascript - 延迟更新 React Native 中的输入文本
- python - 基于另一列值python提取值
- python - 将 numpy recarray 转换为 pyarrow.Table
- html - 页脚是独立的文章吗?
- html - 如何在引导程序上为我的模态添加特定的 css?
- visual-studio - 使用 Visual Studio / CMake / WSL 时如何更改 gcc 编译器版本
- python - 随机替换字符串中的关键字
- python - 如何检查列表中的集合是否是彼此的子集?
- javascript - 分离组件中的 setState
- python-3.x - 使用 for 循环生成字典