简体   繁体   中英

(Fluent) NHibernate mapping for class with calculated properties

I have the a class similar to the following (nb! names have been changed to protect the innocent):

public class Person 
{
    public virtual int Id { get; private set; }
    public virtual string Name { get; set; }
    public virtual DateTime Birthday { get; set; }
    public virtual TimeSpan Age { get { return DateTime.Now - this.Birthday; } }
}

I use Fluent NHibernate to configure my mapping:

public class PersonMap : ClassMap<Person>
{
    public PersonMap() 
    {
        Id(x => x.Id);
        Map(x => x.Name);
        Map(x => x.Birthday);
    }
}

The problem is that this throws an exception:

Could not find a setter for property 'Age' in class 'Person'

If Age is not marked virtual I get:

The following types may not be used as proxies: Person: method get_Age should be 'public/protected virtual' or 'protected internal virtual'

Of course it cant find a setter and it shouldn't! How can I make this mapping work?

The real question to me is why is fluent NHibernate trying to map the Age property at all? It's not even in your mapping. I've only used earlier versions of fluent NHibernate, prior to the whole auto-mapping functionality, and never had this problem.

I suspect that either your Conventions are causing it to try to map Age, or you somehow have auto-mapping enabled which is conflicting with your manual mapping.

Also be aware that Fluent NHibernate somewhat recently changed conventions. So I would take a look at the following documentation:

http://wiki.fluentnhibernate.org/show/Conventions

http://wiki.fluentnhibernate.org/show/ConvertingToNewStyleConventions

http://wiki.fluentnhibernate.org/show/AutoMapping

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM