NHibernate映射属性取决于另一个属性

时间:2012-03-09 14:15:49

标签: nhibernate nhibernate-mapping

我有以下课程:

public class Widget {        
    public virtual int Id { get; set; }

    [Required]
    public virtual WidgetType Type { get; set; }

    public virtual string SerializedParameters {
        get {
            return new XmlSerializer(Parameters.GetType()).Serialize(Parameters);
        } set {
            Parameters = new XmlSerializer(Assembly
                     .LoadFrom(Server.MapPath(Type.ModelAssembly))
                         .GetType(Type.ModelClass)
                ).Deserialize(value);
        }
    }

    private object _parameters;
    public virtual object Parameters {
        get {
            if (_parameters == null)
                _parameters = Activator.CreateInstance(Assembly
                        .LoadFrom(Server.MapPath(Type.ModelAssembly))
                            .GetType(Type.ModelClass)
                    );
            return _parameters;
        } set { _parameters = value; }
    }
}

Parameters属性未映射到数据库,但SerializedParameters属性为。但是,当它尝试从数据库获取信息并设置SerializedParameters(随后设置参数)时,Type属性为null,因此抛出异常。我想这取决于NHibernate为Widget设置属性的顺序,但我无法让它工作。

我想知道是否有办法解决这个问题。感谢帮助。感谢

1 个答案:

答案 0 :(得分:0)

从setter中移除了getter中的反序列化,因为正如你所说的类型还没有

public class Widget
{
    public virtual int Id { get; set; }
    public virtual WidgetType Type { get; set; }

    private string _serializedParameters;
    private virtual string SerializedParameters {
        get
        {
            return new XmlSerializer(Parameters.GetType()).Serialize(Parameters);
        }
        set
        {
            _serializedParameters = value;
        }
    }
    private object _parameters;
    public virtual object Parameters
    {
        get
        {
            if (_parameters == null)
            {
                if (!string.IsNullOrEmpty(serializedParameters))
                {
                    // code to deserialize the Parameters and set to Parameters
                    _parameters = new XmlSerializer(Assembly
                             .LoadFrom(Server.MapPath(Type.ModelAssembly))
                             .GetType(Type.ModelClass)
                         ).Deserialize(value);
                }
                else
                {
                    // no existing parameters, then create new object
                    _parameters = Activator.CreateInstance(Assembly.LoadFrom(Server.MapPath("~/bin/" + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass));
                }
            }
            return _parameters;
        }
        set { _parameters = value; }
    }
}