【发布时间】:2021-09-20 08:07:51
【问题描述】:
我想知道在使用 ADO.NET 从存储过程中读取数据时如何映射外键对象。我无法将Dependent 的响应映射为响应对象的对象列表。我已将其他字段映射到响应对象中。请帮帮我。我是 ADO.NET 的新手。
这些是我的模型类
public class Employee{
public int Id {get; set;}
public string Name {get; set;}
//I don't know how to map response for this property.
public virtual ICollection<Dependent> Dependent {get; set; }
}
public class Dependent {
public int Id {get; set;}
public int EmployeeId {get; set;}
public string Name {get; set; }
}
存储过程
Create procedure spGetEmployeeAll
as
begin
Select * from Employee
inner join Dependent
on Employee.Id = Dependent.EmployeeId
end
存储库类
public Class EmployeeRepositroy : IEmployeeRespository{
private readonly string _connectionString;
public EmployeeRepository(IConfiguration configuration){
_connectionString = configuration.GetConnectionString("TestDatabase");;
}
public Employee GetAll(){
Employee response = new Employee ();
using (SqlConnection sql = new SqlConnection(_connectionString)) {
using (SqlCommand cmd = new SqlCommand("spGetEmployeeAll ", sql)) {
cmd.CommandType = System.Data.CommandType.StoredProcedure;
sql.Open();
using (var reader = cmd.ExecuteReader()) {
response.Id = Convert.ToInt32(reader["ID"]);
respone.Name = Convert.ToString(reader["Name"]);
//How to map Dependent details into the response object?
}
sql.close();
}
}
return response;
}
}
【问题讨论】:
-
我们没有您的表架构,
Dependent在这里指的是什么?Select * from Employee绝对没有给我们提供任何信息,无论如何you shouldn't useselect * -
@Charlieface Dependent 是另一个表,其中包含用于存储员工家属信息的姓名和员工 ID。他们是一对一的关系。
-
好吧,我们不知道如何加入它。您实际上并没有在存储过程中查询它,因此它无法在 ADO.Net 中映射,数据根本不存在
-
好的,我知道了。我必须加入查询中的表,以便结果将包含从属表的详细信息。谢谢。
-
要么返回第二个
select并使用reader.NextResult()检索并使用Dictionary或类似方法进行映射
标签: c# .net-core stored-procedures ado.net