5

我想创建一个 WCF 服务,它使用实体框架调用 SQL Server 中的存储过程并将结果集返回给浏览器。

我使用 EF 中的函数 import 导入了存储过程,并构建了一个复杂类型。

似乎 EF 中的复杂类型无法被序列化并安静地返回。我完成这项工作的唯一方法是创建一个具体类并从 EF 返回的复杂类型构建它。这可行,但这意味着如果我有 30 个存储过程,我需要创建 30 个具体的类,这有点痛苦。

有一个更好的方法吗?

WCF 合同:

[ServiceContract]
public interface IService1
{
    [OperationContract,WebGet,XmlSerializerFormat]
    List<People> usp_GetPeople();    
}

需要为每个过程创建具体类:

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 服务:

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;
    }
}
4

1 回答 1

1

答案是返回一个 EF 复杂类型的列表。

 public List<usp_GetPeople_Result> usp_GetPeople2()
    {
        using (var db = new demoEntities())
        {
            return db.usp_GetPeople().ToList();
        }
    }

这将不起作用:

 public ObjectResult<usp_GetPeople_Result> usp_GetPeople3()
    {
        using (var db = new demoEntities())
        {
            return db.usp_GetPeople();
        }
    }
于 2012-10-22T17:11:30.590 回答