本文介绍了使用Fluent NHibernate映射只读属性而不使用setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的域类。我希望NHibernate在插入/更新时保存

ReadOnly 指示Fluent NHibernate不寻找这个属性的变化,这并不等同于编译器环境中的只读属性。你的财产是不是只读在NHibernate的眼睛,因为你期待它从你的数据库填充。你需要做的是告诉NHibernate,它应该通过一个私有字段与属性相同的名称(小写)访问该属性的值。

  Map(x => x.LastUpdate)
.Access.Field();

使用 Field 哪一个你使用将取决于你如何命名你的私人领域。


I have a domain class that looks like this. I want NHibernate to save the current value of LastUpdate when inserting/updating so that I can use it in queries, but to ignore it when retrieving a Foo from the database and let the object itself recalculate the value when I actually access it.

public class Foo {
    public DateTime LastUpdate {
        get {
            /* Complex logic to determine last update by inspecting History */
            return value;
        }
    }
    public IEnumerable<History> History { get; set; }
    /* etc. */
}

My mapping for Foo looks like this:

public class FooMap : ClassMap<Foo> {
    Map(x => x.LastUpdate)
        .ReadOnly();
    HasMany(x => x.History);
    // etc...
}

I thought that ReadOnly() was what I wanted to accomplish this, but when I try to create a SessionFactory I get the following exception:

The property doesn't have a setter because it shouldn't be set, only read from. Is ReadOnly() the correct thing to do here? If not, what?

(NHibernate v3.0b1, Fluent NHibernate v1.1)

解决方案

ReadOnly instructs Fluent NHibernate to not look for changes on this property, this does not equate to a read-only property in compiler-world. Your property isn't read-only in NHibernate's eyes because you're expecting it to be populated from your database. What you need to do is tell NHibernate that it should access the value of that property through a private field with the same name (lowercased) as the property.

Map(x => x.LastUpdate)
  .Access.Field();

There are several alternatives to using Field, which one you use will depend on how you name your private fields.

这篇关于使用Fluent NHibernate映射只读属性而不使用setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:51