朋友们 过去一周我一直在工作WCF。我写了一些样本,它包含2层,一层是业务层和一层DAL层。我想发送列表并希望返回列表。
这是代码检查纠正错误。
IEmployee.cs
[OperationContract]
List<outEmployee> CreateEmployeeDetails(inemployee InsertEmployee);
[DataContract]
public class inemployee
{
public string EmployeeID { get; set; }
public string EmployeeName { get; set; }
}
public class outEmailTemplate
{
public string EmployeeID { get; set; }
public string EmployeeName { get; set; }
}
Employee.svc.cs
public List<outEmployee> CreateEmployeeDetails(inemployee InsertEmployee)
{
EmployeeDac emp = new EmployeeDac();
return emp.InsertEmployeeDetails(InsertEmployee);
}
EmployeeDac.cs
public List<outEmployee> InsertEmailTemplate(inEmployee InsertEmp)
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd;
cmd = new SqlCommand("SP_InsertEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("employeename", SqlDbType.VarChar).Value = InsertEmp.Employeename;
con.Open();
string id = (string)cmd.ExecuteScalar();
con.Close();
List<inemployee> oet = new List<inemployee>();
oet.Add(id);
return oet;
}
任何人都可以纠正错误并重写代码。
这里我想将列表返回给ui(silverlight)。
答案 0 :(得分:1)
几个问题:
1)数据合同不完整 - 首先需要修饰服务方法中使用的所有类(输入和使用[DataContract]
输出参数!),你还应该用[DataMember]
装饰要序列化的所有成员:
[DataContract]
public class inemployee
{
[DataMember]
public string EmployeeID { get; set; }
[DataMember]
public string EmployeeName { get; set; }
}
[DataContract]
public class outemployee
{
[DataMember]
public string EmployeeID { get; set; }
[DataMember]
public string EmployeeName { get; set; }
}
BTW:为什么你有两种不同的类型 - inemployee
和outemployee
??不只是一种Employee
就足够了吗?
2)您的DAL图层应该采用最佳做法:将SqlConnection
和SqlCommand
包装成使用块;对于VARCHAR
参数,始终定义长度!最重要的是:如果你想返回List<outemployee>
,你需要创建一个outemployee
的列表 - 而不是inemployee
!
要结束:您正在返回id
类型string
并且您尝试将string
添加到List<outemployee>
- 这将<强大>从不当然是工作!鉴于id
,您需要创建outemployee
的实例,并将 添加到列表中。
public List<outEmployee> InsertEmailTemplate(inEmployee InsertEmp)
{
using(SqlConnection con = new SqlConnection(connectionstring))
using(SqlCommand cmd = new SqlCommand("SP_InsertEmployee", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("employeename", SqlDbType.VarChar, 100).Value = InsertEmp.Employeename;
con.Open();
string id = (string)cmd.ExecuteScalar();
con.Close();
}
// you want to return outemployee -
// so you need to create an outemployee!
List<outemployee> oet = new List<outemployee>();
// create a new instance of an "outemployee"
outemployee emp = new outemployee();
// set the EmployeeID property of the "outemployee" to "id"
emp.EmployeeID = id;
// add new "outemployee" to list
oet.Add(emp);
return oet;
}