两个不同DataContracts之间的对象反序列化问题

时间:2019-05-07 23:43:29

标签: c# wcf

在我的解决方案体系结构中,我关注: enter image description here

我遇到对象反序列化问题。在反序列化过程中,我的客户端应用程序出现以下异常。

{“无法使用DataContractSerializer反序列化具有根名称'User'和根名称空间'http://schemas.datacontract.org/2004/07/ECMS.Business.Entities'(用于操作'Login'和合同('ISecurityService','http://tempuri.org/')的XML主体) 。确保将与XML对应的类型添加到服务的已知类型集合中。“}

ECMS.Business.Entities 项目中,我具有以下实体

[DataContract]
public class User : IIdentifiableEntity
{
    [DataMember]
    public int Id { get; set; }
    public int EntityId
    {
        get => Id;
        set => Id = value;
    }
    [DataMember]
    public string UserName { get; set; }
    [DataMember]
    public string FullName { get; set; }
    public string Password { get; set; }
    [DataMember]
    public int Role { get; set; }
    public bool IsActive { get; set; }

    public ICollection<UserSession> Sessions { get; set; }
    public ICollection<Visit> Visits { get; set; }
}

我需要以以下实体的身份返回到客户端(ECMS.Client.Entities项目)

[DataContract]
public class User : ObjectBase
{
    private int _id;

    [DataMember]
    public int Id
    {
        get => _id;
        set
        {
            if (_id != value)
            {
                _id = value;
                OnPropertyChanged();
            }
        }
    }

    private string _userName;

    [DataMember]
    public string UserName
    {
        get => _userName;
        set
        {

            if (_userName != value)
            {
                _userName = value;
                OnPropertyChanged();
            }
        }
    }

    private string _fullName;

    [DataMember]
    public string FullName
    {
        get => _fullName;
        set
        {
            if (_fullName != value)
            {
                _fullName = value;
                OnPropertyChanged();
            }
        }
    }

    private int _role;
    [DataMember]
    public int Role
    {
        get => _role;
        set
        {
            if (_role != value)
            {
                _role = value;
                OnPropertyChanged();
            }
        }
    }
}

[DataContract]
public abstract class ObjectBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

1 个答案:

答案 0 :(得分:2)

使用单独的服务器和客户端合同时,DataContact命名空间必须匹配!

来自here

  

要使数据合同等效,它们必须具有相同的名称空间   和名字