c# - 插入方法有效,但 GET 方法无效
问题描述
我正在使用 WCF 对 Northwind 数据库进行 CRUD 操作。
首先,我创建了 POST 方法,当我使用 WCF 测试客户端尝试它时该方法有效,但 get 方法显示此错误:
调用服务失败。可能原因:服务离线或无法访问;客户端配置与代理不匹配;现有代理无效。有关更多详细信息,请参阅堆栈跟踪。您可以尝试通过启动新代理、恢复到默认配置或刷新服务来恢复。
我不知道是否要让 ViewModel 具有与Employees 类相同的属性,然后对其进行迭代并显示结果?
这是配置文件
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" sendTimeout="00:05:00" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:55658/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="IService1"
name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>
这是get方法:
public IEnumerable<Employee> GetEmployees()
{
List<Employee> list = new List<Employee>();
NorthwindContext db = new NorthwindContext();
list = db.Employees.ToList();
return list;
}
这是服务:
[ServiceContract]
public interface IService1
{
[OperationContract]
IEnumerable<Employee> GetEmployees();
[OperationContract]
void InsertEmployee(Employee e);
[OperationContract]
void UpdateEmployee(Employee e);
[OperationContract]
void DeleteEmployee(int id);
}
更新
好的,我解决了,问题是 Employee 类有外键,客户端无法“读取”它,它显示错误,因为他不知道如何读取该属性。
我所做的只是创建了 EmployeeView 类并插入了我想要显示的属性。
获取方法现在看起来像这样
public IEnumerable<EmployeeView> GetEmployees()
{
NorthwindContext db = new NorthwindContext();
IQueryable<EmployeeView> list = db.Employees.Select(e => new EmployeeView
{
EmployeeID = e.EmployeeID,
FirstName = e.FirstName,
LastName = e.LastName
});
return list;
}
解决方案
如果员工有另一个表的外键,则会出现解析错误。您需要为员工类创建另一个模型 dto
模型:
public int EmployeeId {get;set;}
public ICollection<Order> Orders{get;set;} // this causes to parse error. Because this object have ICollection<Employee> and this causes infinite loop
模型Dto:
public int EmployeeId {get;set;}
或者如果您想发送订单,您可以创建另一个 dto
推荐阅读
- css - CSS计数器不递增
- php - 将子类中的父变量分配为php中的传递实例
- php - 写入 .txt 文件,但我的 while 循环是无限的
- angularjs - 使用 Selenium webdriver 调用在 Angularjs 控制器中定义的函数
- vba - 使用函数在某些外部excel文件中查找数据
- python - 为什么我在 LeetCode 上的解决方案不起作用(递归、python)?
- r - 以编程方式创建新变量,这些变量是其他变量的嵌套系列之和
- pdf - 在 Google 表格中,我可以使用脚本将单元格中的所有函数替换为它们计算的纯文本或数字值吗?
- twitter-bootstrap-3 - Boostrap 3.0 两列布局
- javascript - Tradingview 小部件 - 自定义简单移动平均线和指数移动平均线长度