[NHibernate] One-to-many, demande de vérification
Bonjour,
Je voudrais savoir si ce que j'ai fais est correct, surtout au niveau de l'ajout des données. Ça fonctionne mais je suis pas sur que ce soit la bonne méthode.
C'est un application console, je n'ai pas fais de bibliothèque de classes, de repositories et d'interface (c'est un peu à la sauvage...mais bon)
Code:
1 2 3 4 5 6 7
| public class Users
{
public virtual int user_Id { get; private set; }
public virtual string user_Name { get; set; }
public virtual string user_Sex { get; set; }
public virtual IList<Phones> phone { get; set; }
} |
Code:
1 2 3 4 5 6 7
| public class Phones
{
public virtual int phone_Id { get; private set; }
public virtual string phone_Number { get; set; }
public virtual DateTime phone_Date { get; set; }
public virtual Users user { get; set; }
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="ConsoleNhibernate.Mappings"
assembly="ConsoleNhibernate">
<class name="Users" table="Users">
<id name="user_Id" column="User_Id">
<generator class="identity"/>
</id>
<property name="user_Name" column="User_Name"/>
<property name="user_Sex" column="User_Sex"/>
<bag name="phone" cascade="all-delete-orphan" lazy="false">
<key column="User_Id" not-null="true"/>
<one-to-many class="Phones"/>
</bag>
</class>
</hibernate-mapping> |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="ConsoleNhibernate.Mappings"
assembly="ConsoleNhibernate">
<class name="Phones" table="Phones">
<id name="phone_Id" column="Phone_Id">
<generator class="identity"/>
</id>
<property name="phone_Number" column="Phone_Number"/>
<property name="phone_Date" type="timestamp" column="Phone_Date"/>
<many-to-one name="user" class="Users" column="User_Id" cascade="none" not-null="true"/>
</class>
</hibernate-mapping> |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| Users classUser = new Users()
{
user_Name = "toto",
user_Sex = "M"
};
Phones phone = new Phones()
{
phone_Number = "06 06 06 06 06",
phone_Date = DateTime.Now,
user = classUser
};
insertItemUsers(classUser);
insertItemPhones(phone); |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| private static void insertItemUsers(Users user)
{
using (ISession session = hibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(user);
transaction.Commit();
}
}
}
private static void insertItemPhones(Phones phone)
{
using (ISession session = hibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(phone);
transaction.Commit();
}
}
} |
Merci de m'aider.