我该如何映射存储过程结果与LINQ到SQL自定义类? [英] How can I map stored procedure result into a custom class with linq-to-sql?

查看:162
本文介绍了我该如何映射存储过程结果与LINQ到SQL自定义类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储过程返回结果集(4列×n行)。该数据是根据我的数据库内的多个表,并提供内的企业每个部门的摘要。下面是示例:

I have a stored procedure that returns a result set (4 columns x n Rows). The data is based on multiple tables within my database and provides a summary for each department within a corporate. Here is sample:

usp_GetDepartmentSummary

DeptName      EmployeeCount      Male      Female
HR            12                 5         7
etc...

我使用LINQ到SQL检索我的数据库中的数据(注: - 必须使用存储过程,因为它是我继承)。我想调用上面的存储过程,并映射到一个部门级的:

I am using linq-to-sql to retrieve data from my database (nb - have to use sproc as it is something I have inherited). I would like to call the above sproc and map into a department class:

public class Department
{
     public string DeptName {get; set;}
     public int EmployeeCount {get; set;}
     public int MaleCount {get; set;}
     public int FemaleCount {get; set;}
}

在VS2008中,我可以将我的存储过程拖放到LINQ到SQL设计方法窗格中。当我检查 designer.cs 此存储过程返回类型被定义为:

In VS2008, I can drag and drop my sproc onto the methods pane of the linq-to-sql designer. When I examine the designer.cs the return type for this sproc is defined as:

ISingleResult<usp_GetDepartmentSummaryResult>

我想要做的就是以某种方式修改本,使其返回键入,这样我可以通过存储过程作为一个强类型的视图的结果:

What I would like to do is amend this somehow so that it returns a Department type so that I can pass the results of the sproc as a strongly typed view:

<% foreach (var dept in Model) { %>
<ul>
    <li class="deptname"><%= dept.DeptName %></li>
    <li class="deptname"><%= dept.EmployeeCount %></li>
    etc...

任何想法如何实现这一目标?

Any ideas how to achieve this?

NB - 我曾尝试修改 designer.cs dbml的xml文件直接但收效甚微。我承认是我深一点点出来,当涉及到直接更新这些文件,我不知道它是最好的做法?将是很好的得到一些diretion。

NB - I have tried amending the designer.cs and dbml xml file directly but with limited success. I admit to being a little out of my depth when it comes to updating those files directly and I am not sure it is best practice? Would be good to get some diretion.

谢谢了

推荐答案

手工创建的LINQ2SQL生成器中的类,因此该类作为LINQ2SQL数据上下文的一部分生成。将类命名部,你想要的名称添加的每个4个属性。在每个属性的属性,你需要设置类型(.NET类型),和服务器的数据类型(VARCHAR(100),int)和源(由存储过程返回的字段的名称。)

create the class by hand in the linq2sql builder, so the class is generated as part of the linq2sql data context. name the class Department, add each of the 4 properties with the names you want. in each of the properties' properties, you need to set the type (the .net type), and the Server data type (varchar(100), int) and the source (the name of the field returned by the sproc.)

一旦这样做了,拖从服务器资源管理器中存储过程到这个类,并为存储过程的方法将返回一个结果作为该类型的集合。

once that's done, drag the sproc from server explorer onto that class, and the method for the sproc will return a result as a collection of that type.

这篇关于我该如何映射存储过程结果与LINQ到SQL自定义类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆