1

我可以有这样的条件吸气剂:

我需要检查一个属性是否为空,如果它的空返回同一类的另一个属性。

这是一个用于 nHibernate 映射的类。

public virtual District District 
        {
            get 
            {
                return this.District == null ? this.Zone : this.District; 
            } 
            set
            {
                this.District = value;
            }
        }

当我尝试这个时,服务器只是挂断了......

4

3 回答 3

4

您已经递归地定义了您的属性(getter 和 setter 实际上都调用了自己)。您需要使用内部字段来存储实际值:

private District district;

public virtual District District 
{
    get 
    {
        return this.district ?? this.Zone; 
    } 
    set
    {
        this.district = value;
    }
}
于 2013-09-05T00:32:07.863 回答
2

在 NHibernate 映射的情况下,我不会向映射属性添加任何逻辑。在这种情况下,我会添加一个不同的方法:

public virtual District District  { get; set; }

public virtual District GetDistrictOrDefault()
{
    return District ?? this.Zone;
}

或者您可能想要保护映射的 District-Property - 您可以提供第二个包装受保护的属性提供一些逻辑:

// Mapped with NHibernate
protected virtual District District  { get; set; }

public virtual District DistrictOrDefault // You might find a better naming... 
{
    get 
    {
        return District ?? this.Zone; 
    } 
    set
    {
        District = value;
    }
}
于 2013-09-05T06:43:40.010 回答
1

It's possible and quite simple to do just that. NHibernate allows us to specify access strategy for individual property. I'm frequently use something like this:

protected District _district;
public virtual District District 
{
    get { return _district ?? this.Zone; }
    set { _district = value; }
}

And mapping for the property:

<property name="District" access="field.camelcase-underscore" />

In this mapping scheme, your code will use the property to get/set data, while NHibernate uses the field to do the same. If you leave out the access setting, in case the property District is really NULL, NHibernate will think that you have changed the property District to the new value and it will try to update the corresponding database record. This might result in bugs. I've never used Fluent NHibernate, so I don't know how to do that with Fluent.

于 2013-09-09T06:56:51.793 回答