【问题标题】:How to Convert object result model to a custom view model in asp .net MVC 5如何在 asp .net MVC 5 中将对象结果模型转换为自定义视图模型
【发布时间】:2023-03-18 02:25:01
【问题描述】:

我已经完成了一个使用存储过程通过实体框架显示连接表值的项目。 我已经完成了所有基本过程,并且在从我的模型中调用它时,它成功返回了对象结果,

现在我的问题是我无法将该结果模型从具有复杂返回类型的存储过程转换为我的视图模型。 谁能帮我解决一下。

我在下面附上了我的项目工作,

这是 ADO .net 实体模型自动生成的上下文

模型浏览器函数导入中的编辑函数

显示自动生成的结果。

这就是我想要做的事情

这是我遇到的错误

这就是我的视图模型的组成

存储过程查询(Mysql)

【问题讨论】:

  • 您必须在.Select() 中为您的ViewModel 提供映射,例如:var query = objEmployee.sp_display().Select(s=>new ViewModel{employees=new employee{//add the mapping properties here},employee_detail = new employee_detail{//add the mapping properties here}}).ToList()
  • @vikscool 你能给我看一个添加映射属性位置的示例,我在员工表中有姓名和部门,在员工详细信息中有地址和手机

标签: c# asp.net asp.net-mvc asp.net-mvc-5 ado.net-entity-data-model


【解决方案1】:

正如 OP 在评论中提到的,employeeemployee_details 的架构类似于:

public class employee
{
    public string Name {get;set;}
    public string Department {get;set;}
}

public class employee_details
{
    public string Address {get;set;}
    public string Mobile {get;set;}
}

因此,应用映射后,您的代码将如下所示:

var query = objEmployee.sp_display().Select(s=> new ViewModel{
employees = new employee{
 Name = s.Name //change the s.Name to the property name coming from your SP(if different)
 Department = s.Department
},
employee_detail = new employee_detail{
  Address = s.Address,
  Mobile = s.Mobile
}}).ToList()

或者最好只删除query 对象并使用listEmployeeList,因为此列表本身也引用ViewModel,因此query 对象是不必要的(除非你想做其他的过滤就可以了):

listEmployeeList = // the above code with .ToList();

【讨论】:

  • 正如我在第三张图片中显示的那样,如果存储过程返回值,则没有写入任何属性。由于它是自动生成的,如果我们手动定义属性,任何未来的更改都将被覆盖,即使我手动定义了它,它分配了“listEmployeeList”的索引列表的数量,但它不存储任何值,它只显示一个空值.在模型创建过程中我是否遗漏了任何映射?
  • 它将显示 null 因为您没有在 sp_display_result 类中定义属性。如果列可以从Procedure 更改,那么ViewModel 类也必须更改。因此,最好在sp_display_result 类中提供映射属性。否则使用DataTable 捕获数据,然后将其转换为json 并将其传递给业务逻辑中的客户端/句柄以支持映射。
  • 由于程序中没有输入参数,如何用sp_display_result进行映射。有什么方法可以映射。
猜你喜欢
  • 2011-03-22
  • 2021-04-23
  • 2012-03-25
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 2013-03-27
  • 2013-03-25
  • 1970-01-01
相关资源
最近更新 更多