I want to create a WCF service that calls a stored procedure in SQL Server using the Entity Framework and returns the result set to a browser.
我想创建一个WCF服务,使用Entity Framework调用SQL Server中的存储过程,并将结果集返回给浏览器。
I imported the stored procedure using the function import in EF and I built a complex type.
我使用EF中的函数import导入了存储过程,并构建了一个复杂类型。
It seems that a complex type from the EF cannot be serialized and returned restfully. The only way I have made this work is to create a concrete class and build it from the complex type returned from EF. This works but it means if I have 30 stored procedures I would need to create 30 concrete classes which is somewhat of a pain.
似乎EF中的复杂类型无法序列化并且可以重新返回。我完成这项工作的唯一方法是创建一个具体的类,并从EF返回的复杂类型构建它。这有效,但这意味着如果我有30个存储过程,我需要创建30个具体的类,这有点痛苦。
Is there a better way to do this?
有一个更好的方法吗?
WCF contract:
[ServiceContract]
public interface IService1
{
[OperationContract,WebGet,XmlSerializerFormat]
List<People> usp_GetPeople();
}
Concrete class would need to be created for every procedure:
需要为每个过程创建具体类:
public class People
{
public int person_id;
public string last_name;
public string first_name;
public string street_addr;
public string state_code;
public string postal_code;
public People(int person_id, string last_name, string first_name, string street_addr, string state_code, string postal_code)
{
this.person_id = person_id;
this.last_name = last_name;
this.street_addr = street_addr;
this.state_code = state_code;
this.postal_code = postal_code;
}
public People() { }
}
WCF service:
public class Service1 : IService1
{
/// <summary>
/// Call stored proc and return resultset.
/// </summary>
/// <returns>List of resultset as concrete class People.</returns>
public List<People> usp_GetPeople()
{
try
{
using (var db = new demoEntities())
{
var res = db.usp_GetPeople();
List<People> lst = new List<People>();
foreach (usp_GetPeople_Result r in res)
{
People p = new People(r.person_id, r.last_name, r.first_name, r.street_addr, r.state_code, r.postal_code);
lst.Add(p);
}
return lst;
}
}
catch (Exception e)
{
Utility.Log("Error in usp_GetPeople. " + e.ToString());
return null;
}
}
1 个解决方案
#1
1
Answer is to return a List of the EF complex type.
答案是返回EF复杂类型的List。
public List<usp_GetPeople_Result> usp_GetPeople2()
{
using (var db = new demoEntities())
{
return db.usp_GetPeople().ToList();
}
}
This will not work:
这不起作用:
public ObjectResult<usp_GetPeople_Result> usp_GetPeople3()
{
using (var db = new demoEntities())
{
return db.usp_GetPeople();
}
}
#1
1
Answer is to return a List of the EF complex type.
答案是返回EF复杂类型的List。
public List<usp_GetPeople_Result> usp_GetPeople2()
{
using (var db = new demoEntities())
{
return db.usp_GetPeople().ToList();
}
}
This will not work:
这不起作用:
public ObjectResult<usp_GetPeople_Result> usp_GetPeople3()
{
using (var db = new demoEntities())
{
return db.usp_GetPeople();
}
}