学习阶段,如果哪里写的不对,或者是把简单的东西复杂化了,欢迎来指正。
1.现在有两个表,一个表是UserManagement,一个表是DepartManagement,我现在需要把这两个表的数据关联起来。新建一个类UserDto用于关联这两个类
public partial class UserManagement
{
public string UserId { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
public int? Permission { get; set; }
public string DepartID { get; set; }
}
public class DepartManagement
{
public string DepartmentID { get; set; }
public string DepartmentName { get; set; }
}
public class UserDto
{
public string UserId { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
public int? Permission { get; set; }
public string DepartID { get; set; }
public string DepartName { get; set; }
}
2.现在开始写后端代码了
(1)首先在BLL中写增删改查事件
/// <summary>
/// 多表联查
/// </summary>
/// <param name="dbcontext"></param>
/// <param name="model"></param>
/// <returns></returns>
public static List<UserDto> UserIndex(testContext dbcontext, UserDto model, PageDto pageDto)
{
List<UserDto> tusers = null; // 初始化为列表类型
try
{
//lambda
if (model != null && !string.IsNullOrEmpty(model.UserName))
{
var a = dbcontext.UserManagements.Join(dbcontext.DepartManagements, t => t.DepartID, s => s.DepartmentID, (t, s) => new UserDto
{
UserId = t.UserId,
UserName = t.UserName,
PassWord = t.PassWord,
DepartID = t.DepartID,
DepartName = s.DepartmentName,
});
tusers = a.Where(m => m.UserId.Contains(model.UserId)).ToList(); // 转换为列表类型
}
else
{
var a = dbcontext.UserManagements.Join(dbcontext.DepartManagements, t => t.DepartID, s => s.DepartmentID, (t, s) => new UserDto
{
UserId = t.UserId,
UserName = t.UserName,
PassWord = t.PassWord,
DepartID = t.DepartID,
DepartName = s.DepartmentName,
});
tusers = a.ToList(); // 转换为列表类型
}
}
catch (Exception ex)
{
// 异常处理
}
return tusers;
}
(2)在Controller中向前端发送数据
//多表联查---查询
[HttpPost]
public List<UserDto> GetMoreLocation([FromBody] UserDto model)
{
dbcontext = new testContext();
PageDto pageDto=new PageDto();
List<UserDto> towerInfoList = UserBll.UserIndex(dbcontext, model, pageDto).ToList();
return towerInfoList;
}
3.后端的代码写完了,接下来写前端的代码(javaScript)
data () {
return{
titles:"新增用户",
tableDatas:[],
locUsers:[],
tableData:{
userId:"",
username:"",
password:"",
departId:"",
},
dialogFormVisible:false,
}
},
methods: {
getUsers() {
this.axios.post("https://localhost:56987/api/User/GetMoreLocation", {})
.then((response) => {
console.log(response);
this.tableDatas = response.data;
console.log("执行");
console.log(tableDatas);
console.log(this.tableDatas);
console.log("1");
this.showplay();
})
.catch(error => {
console.log("错误");
console.log(error);
});
},
}