Search code examples
c#nhibernate

Proper Guid Mapping. Nhibernate


I use an abstract Entity class which contains a Guid:

public abstract class Entity
{
    public /*virtual*/ Guid Id { get; set; }
}

Suppose I also have a class like:

public class Post : Entity
{
    public String Title { get; set; }
    public String Content { get; set; }
    public DateTime Timestamp { get; set; }
}

How do I properly map Post class using xml-mapping? I'm asking about Id.


Solution

  • <id name="Id">
        <generator class="guid"/>
    </id>
    

    This will generate Guids on the client using the Guid.NewGuid() method.

    Alternative generators are:

    • guid.native - generates the Guids on the server side, e.g. using NEWID() on SQL server
    • guid.comb - generates "sequential" Guids, which reduces index fragmentation.

    I would recommend guid.comb for most applications that use Guid identifiers.