Nhibernate Guid with PK MySQL
I've got a question. I use NHibernate with MySql. At my entities I use Id(PK) for my business-logic usage and Guid(for replication). So my BaseDomain:
public class BaseDomain
{
public virtual int Id { get; set; }
public virtual Guid Guid { get; set; }
public class Properties
{
public const string Id = "Id";
public const string Guid = "Guid";
}
public BaseDomain() { }
}
My usage domain:
public class ActivityCategory : BaseDomain
{
public ActivityCategory() { }
public virtual string Name { get; set; }
public new class Properties
{
public const string Id = "Id";
public const string Guid = "Guid";
public const string Name = "Name";
private Properties() { }
}
}
Mapping:
开发者_如何学Go <class name="ActivityCategory, Clients.Core" table='Activity_category'>
<id name="Id" unsaved-value="0" type="int">
<column name="Id" not-null="true"/>
<generator class="native"/>
</id>
<property name="Guid"/>
<property name="Name"/>
</class>
But when I insert my entity:
[Test]
public void Test()
{
ActivityCategory ac = new ActivityCategory();
ac.Name = "Test";
using (var repo = new Repository<ActivityCategory>())
repo.Save(ac);
}
I always get '00000000-0000-0000-0000-000000000000' at my Guid field. What should I do for generate right Guid. May be mapping?
Thanks a lot!
From a NHibernate perspective, you should either set the guid in C# or tell NHibernate that it is generated by the database.
In the former case, set the guid property in the constructor.
public class BaseDomain
{
public BaseDomain()
{
Guid = Guid.NewGuid();
}
}
You map a property whose value is generated in the database like this. Depending on how the value is generated, you may also need to exclude the property from insert statements.
<class name="ActivityCategory, Clients.Core" table="Activity_category">
<id name="Id" not-null="true" >
<generator class="native" />
</id>
<property name="Guid" generated="insert" insert="false" update="false" />
<property name="Name" />
</class>
精彩评论