I need to set som default values and I have the following class and mapping respectively.
Farmacia.cs
public class Farmacia
{
public virtual int Id { get; protected set; }
public virtual string Nombre { get; set; }
public virtual string Direccion { get; set; }
public virtual string Telefono { get; set; }
public virtual int CodigoPostal { get; set; }
public virtual int Estado { get; set; }
public Farmacia()
{
}
}
Farmacia.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Domain"
namespace="Domain">
<class name="Farmacia" table="farmacias">
<id name="Id" column="idFarmacia" type="int">
<generator class="assigned" />
</id>
<property name="Nombre" />
<property name="Direccion" />
<property name="CodigoPostal">
<column name="codPostal" default="1"/>
</property>
<property name="Telefono" />
<property name ="Estado">
<column name="estado" default="1" />
</property>
</class>
</hibernate-mapping>
Test
Domain.Farmacia f = new Domain.Farmacia { Nombre = "Test" };
Session.Save(f);
Session.Flush();
And I get a Exception that it cannot insert on database.
On the other hand, if I make some changes in the code (See below) I can save it.
public class Farmacia
{
public virtual int Id { get; protected set; }
public virtual string Nombre { get; set; }
public virtual string Direccion { get; set; }
public virtual string Telefono { get; set; }
public virtual int CodigoPostal { get; set; }
public virtual int Estado { get; set; }
public Farmacia()
{
Estado = 1; // New line.
CodigoPosta = 1; // New line.
}
}
Farmacia.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Domain"
namespace="Domain">
<class name="Farmacia" table="farmacias">
<id name="Id" column="idFarmacia" type="int">
<generator class="assigned" />
</id>
<property name="Nombre" />
<property name="Direccion" />
<property name="CodigoPostal" column="codPostal" /> // Property changed.
<property name="Telefono" />
<property name ="Estado" /> // Property changed.
</class>
</hibernate-mapping>
My problem is that I need the default values only if the object is new. If the object is already on the database, Always the objects from database will have some values in Estado and CodigoPostal.
P.D: I assigned default value in the database but the error persists.
So how can I set default values if the values are null (Object is new)?
What you’ve done above by putting the default values in the constructor seems fine to me but if you’re looking for another way you might be able to use something like this:
Above was taken from here: http://www.nhforge.org/doc/nh/en/index.html#mapping-declaration-class
The only way you’d be able to use the database defaults though for integer columns would be to make them nullable and use
dynamic-insertsince the default value for an integer is 0.