通过 Wcf 序列化 Linq2Sql - 错误或误解?

2024-03-01

使用 Linq2Sql 作为 Wcf 服务的驱动程序。让我们从下往上......

在底部,我们有调用 Linq2Sql 的方法...

public virtual void UpdateCmsDealer(CmsDealer currentCmsDealer)
{
    this.Context.CmsDealers.Attach(currentCmsDealer, 
             this.ChangeSet.GetOriginal(currentCmsDealer));
}

我的 Wcf 服务会使用它......

public bool UpdateDealer(CmsDealer dealer)
{
    try
    {
        domainservice.UpdateCmsDealer(dealer);
        return true;
    }
    catch
    {
        return false;
    }
}

并从我的 Wpf 客户端代码调用(下面的伪代码)...

[...pull the coreDealer object from Wcf, it is a CmsDealer...]
[...update the coreDealer object with new data, not touchign the relation fields...]
try
{
    contextCore.UpdateDealer(coreDealer);
}
catch (Exception ex)
{
    [...handle the error...]
}

现在,CmsDealer 类型具有 >1

现在,事情是这样的...如果你注释掉该行...

domainservice.UpdateCmsDealer(dealer);

在 Wcf 服务中,它仍然会爆炸,但有以下例外,这向我表明这并不是真正的 Linq2Sql 问题,而是 Linq2Sql over Wcf 问题。

"System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException was unhandled by user code
  Message="Operation is not valid due to the current state of the object."

内部异常为 NULL。最终结果是,当它冒泡到错误处理程序(Catch ex bloc)时,异常消息将抱怨反序列化器。当我可以进行调试时,引发错误的实际代码是 Linq2Sql 构建的 CmsDealer 模型代码中的这个片段。

[Column(Storage="_StateId", DbType="UniqueIdentifier NOT NULL")]
public System.Guid StateId
{
    get
    {
        return this._StateId;
    }
    set
    {
        if ((this._StateId != value))
        {
            if (this._CmsItemState.HasLoadedOrAssignedValue)
            {
                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
            }
            this.OnStateIdChanging(value);
            this.SendPropertyChanging();
            this._StateId = value;
            this.SendPropertyChanged("StateId");
            this.OnStateIdChanged();
        }
    }
}

简而言之,似乎有些事情正在“幕后”发生,这很好,但文档不存在。谷歌搜索“ForeignKeyReferenceAlreadyHasValueException”几乎什么也没找到:)

我更愿意继续直接通过 Wcf 使用 Linq2Sql 对象。如果需要,我可以创建一个没有关联的平面代理类,将其发送到 Wcf,然后将其用作服务器端更新的数据源......但这似乎需要付出很大的努力,因为显然这是一个预期的场景......对吗?

Thanks!


默认的序列化器会首先设置State,然后再设置StateId。之后它将尝试设置序列化的 StateId,然后抛出异常。

问题是您没有指定您希望用 DataContract 属性来装饰您的类。

转到 LinqToSqlGenerator 的属性并设置序列化模式 to 单向

这将导致该工具将 DataMember 属性添加到所需的属性中,并且您将看到 StateId 将不是 DataMember,因为在反序列化时设置 State 属性时它将自动设置。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 Wcf 序列化 Linq2Sql - 错误或误解? 的相关文章

随机推荐