首页 > 解决方案 > 如何在 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();
        }

    }

有人可以帮我吗?
谢谢 !!

标签: c#linqasp.net-corelinq-to-sqllinq2db

解决方案


推荐阅读