0

Is there a way to avoid the explicit Id mapping in Fluent NHibernate?

I want it to somehow generate the entry id automatically so that I wouldn't have to introduce it as a part of the class.

public class HeyMapping
{
    public String Name { get; set; }
    public DateTime Timestamp { get; set; }
}

public class HeyMapping : ClassMap<HeyMapping>
{
    public HeyMapping()
    {
        Not.LazyLoad();

        // I'm not particularly sure how this line works, but
        // it fails the mapping unit test.
        CompositeId().KeyProperty(x => x.Name);

        Map(x => x.Name).Not.Nullable().Length(64);
        Map(x => x.Timestamp).Not.Nullable();
    }
}

2 Answers 2

2

If you want to have no id in your entity, you still have to map an Id so NHibernate knows the database column to use.

You can call

Id<TColumnDataType>("column_name");

Please note that you will give up some NHibernate functionality (specifically cascading updates and the ability to call SaveOrUpdate()) and incur a performance penalty on the database side for having database-only identity (I believe NHibernate will have to make extra queries for comparison).

I usually concede this point and allow the Id as the one persistence concern in my domain classes, so I would do this:

public class HeyMapping
{
    protected internal int Id { get; set; } // persistence concern

    public virtual String Name { get; set; }
    public virtual DateTime Timestamp { get; set; }
}

I realize you might not want to do this; I'm just letting you know that there is a tradeoff.

Sign up to request clarification or add additional context in comments.

Comments

1

Create a base class from which all of your mapped entities inherit, then add an Id property to your base class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.