从WCF服务器返回的对象为空

时间:2013-06-13 08:25:49

标签: c# wcf automapper dto

在客户端应用程序中,我输入了一个项目ID,并且WCF服务器应该返回一个ItemDTO类型的对象。但是,当回复时,该对象为空。

ItemDTO itm = Connection.Instance.HttpProxy.GetItem(ItemID);

到目前为止我可以确认:

  • 已成功从数据库中取得所请求的项目
  • 映射确实有效(检查生成的映射的内容)
  • 内容确实已发送(使用Fiddler检查) enter image description here

  • 但是,当我检查itm的内容时,它是空的。

这是WCF服务器中的GetItem()方法:

public ItemDTO GetItem(string itemID) {
    using (var db = new PoSEntities()) {
        var query = from i in db.Items
                    where i.ItemID.Equals(itemID)
                    select i;
        Item item = query.FirstOrDefault();
        return item == null ? null : Mapping.Map<Item, ItemDTO>(item);
    }
}

我使用AutoMapper将实体对象映射到DTO:

    public static H Map<T, H>(T i) {
        Mapper.CreateMap<T, H>();
        return Mapper.Map<T, H>(i);
    }

Item类由实体框架生成:

public partial class Item
{
    public Item()
    {
        this.Sal1 = new HashSet<Sal1>();
    }

    public string ItemID { get; set; }
    public string Name { get; set; }
    public string Manufacturer { get; set; }
    public int StockQuantity { get; set; }
    public decimal Price { get; set; }

    public virtual ICollection<Sal1> Sal1 { get; set; }
}

连接类:

 public sealed class Connection {

    private readonly string _address = "http://Edwin:8080/PoS";
    private static Connection _instance;
    private static object _padLock = new Object();
    private static ChannelFactory<IPoS> httpFactory;

    private static IPoS _httpProxy; //Singleton
    public IPoS HttpProxy { get { return _httpProxy; } }

    public static Connection Instance {
        get {
            if (_instance == null) {
                lock (_padLock) {
                    if (_instance == null) {
                        _instance = new Connection();
                    }

                }
            }
            return _instance;
        }
    }

    private Connection() {
        httpFactory = new ChannelFactory<IPoS>(
            new BasicHttpBinding(), 
            new EndpointAddress(_address));
        _httpProxy = httpFactory.CreateChannel();
    }
}

ItemDTO上课:

[DataContract]
public class ItemDTO {
    [DataMember]
    public string ItemID { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Manufacturer { get; set; }
    [DataMember]
    public int StockQuantity { get; set; }
    [DataMember]
    public decimal Price { get; set; }
}

1 个答案:

答案 0 :(得分:0)

最后解决了,解决方案很简单。

只需在两端给DTO类(在本例中为ItemDTO)命名空间 即:[DataContract][DataContract(Namespace"PoSDTO")]