ここでは HBM と FluentNHibernate を使用してエンティティをマッピングしていますが、なぜ HBM はエンティティの ID を自動的に割り当てないのでしょうか? Fluent API は、..
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="XmlMappingSimple.Domain"
assembly="XmlMappingSimple">
<class name="Customer" table="t_Customers" schema="dbo">
<id column="Id" type="Int32" >
<generator class="identity"></generator>
</id>
<property name="CustomerName" length="50" type="string" not-null="true">
</property>
</class>
</hibernate-mapping>
これは私のすべてのC#コードです:
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Mapping;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XmlMappingSimple.Domain;
namespace XmlMappingSimple
{
public class CustomerMap : ClassMap<Customer>
{
public CustomerMap()
{
Id(_ => _.Id)
.GeneratedBy.Identity();
Map(_ => _.CustomerName);
Table("t_Customers");
}
}
class Program
{
static void Main(string[] args)
{
var sessionFactory = new Configuration()
.Configure()
.AddAssembly(typeof(Customer).Assembly)
.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
var cus1 = new Customer { CustomerName = "my name1" };
var cus2 = new Customer { CustomerName = "my name2" };
session.Persist(cus1);
session.Flush();
session.Save(cus2);
session.Flush();
Console.WriteLine("cus1.Id = {0} ", cus1.Id);
Console.WriteLine("cus2.Id = {0} ", cus2.Id);
}
var sessionFactoryForFluent = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(@"Server=.\sql2008;initial catalog=nhibernate;Integrated Security=True"))
.Mappings(_ => _.FluentMappings.AddFromAssemblyOf<Customer>())
.BuildConfiguration().BuildSessionFactory();
Console.WriteLine("Fluent ================");
using (var session = sessionFactoryForFluent.OpenSession())
{
var cus1 = new Customer { CustomerName = "my name1" };
var cus2 = new Customer { CustomerName = "my name2" };
session.Persist(cus1);
session.Flush();
session.Save(cus2);
session.Flush();
Console.WriteLine("cus1.Id = {0} ", cus1.Id);
Console.WriteLine("cus2.Id = {0} ", cus2.Id);
}
}
}
}
これはコンソール出力です:
cus1.Id = 0
cus2.Id = 0
Fluent ================
cus1.Id = 29
cus2.Id = 30
session.Save(cus2)
新しい ID ID が返されることはわかっています, 新しい ID IDがsession.Save (cus2)
返されることはわかってentity.Id
います.