首页 > 解决方案 > 插入方法有效,但 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;
        }

标签: c#.netwcf

解决方案


如果员工有另一个表的外键,则会出现解析错误。您需要为员工类创建另一个模型 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


推荐阅读