本文整理汇总了C#中NHibernate.Cfg.Configuration.BuildSessionFactory方法的典型用法代码示例。如果您正苦于以下问题:C# Configuration.BuildSessionFactory方法的具体用法?C# Configuration.BuildSessionFactory怎么用?C# Configuration.BuildSessionFactory使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类NHibernate.Cfg.Configuration
的用法示例。
在下文中一共展示了Configuration.BuildSessionFactory方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestAccount
public static Boolean TestAccount(DatabaseAccountToken token, Boolean testMapping = false)
{
try
{
Configuration configuration = new Configuration();
configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionString, token.ConnectionString);
configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, String.Format("NHibernate.Driver.{0}", token.DatabaseDriver));
configuration.SetProperty(NHibernate.Cfg.Environment.Dialect, String.Format("NHibernate.Dialect.{0}", token.DatabaseDialect));
if (testMapping)
{
configuration.AddXml(token.Mapping);
using (ISessionFactory sessionFactory = configuration.BuildSessionFactory())
{
using (ISession session = sessionFactory.OpenSession())
{
return session.IsConnected;
}
}
}
else
{
using (ISessionFactory sessionFactory = configuration.BuildSessionFactory())
{
using (ISession session = sessionFactory.OpenSession())
{
return session.IsConnected;
}
}
}
}
catch (Exception ex)
{
return false;
}
}
示例2: CanSetDefaultFlushModeThroughLoquaciousConfiguration
public void CanSetDefaultFlushModeThroughLoquaciousConfiguration()
{
var cfg = new Configuration()
.Configure();
cfg
.SessionFactory()
.DefaultFlushMode(FlushMode.Always);
using (var sessionFactory = cfg.BuildSessionFactory())
{
using (var session = sessionFactory.OpenSession())
{
Assert.AreEqual(FlushMode.Always, session.FlushMode);
}
}
cfg.Configure()
.SessionFactory()
.DefaultFlushMode(FlushMode.Commit);
using (var sessionFactory = cfg.BuildSessionFactory())
{
using (var session = sessionFactory.OpenSession())
{
Assert.AreEqual(FlushMode.Commit, session.FlushMode);
}
}
}
示例3: Init
private static void Init()
{
nhConfiguration = new Configuration();
//nhConfiguration.Configure("NhibernateUtils/NHibernate.cfg.xml");
nhConfiguration.AddAssembly("Activos");
sessionFactory = nhConfiguration.BuildSessionFactory();
}
示例4: InitNHibernate
private static void InitNHibernate()
{
lock (LockObject)
{
if (_sessionFactory == null)
{
// Создание NHibernate-конфигурации приложения на основании описаний из web.config.
// После этого вызова, в том числе, из сборки будут извлечены настройки маппинга,
// заданные в xml-файлах.
var configure = new Configuration().Configure();
// Настройка маппинга, созданного при помощи mapping-by-code
var mapper = new ModelMapper();
mapper.AddMappings(new List<Type>
{
// Перечень классов, описывающих маппинг
typeof (DocumentTypeMap),
typeof (DocumentMap),
typeof (DocumentWithVersionMap),
});
// Добавление маппинга, созданного при помощи mapping-by-code,
// в NHibernate-конфигурацию приложения
configure.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null);
//configure.LinqToHqlGeneratorsRegistry<CompareValuesGeneratorsRegistry>();
//configure.LinqToHqlGeneratorsRegistry<InGeneratorRegistry>();
configure.DataBaseIntegration(x =>
{
x.LogSqlInConsole = true;
x.LogFormattedSql = true;
});
_sessionFactory = configure.BuildSessionFactory();
}
}
}
示例5: SaveExamUser
/// <summary>
/// 保存考试人信息
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static int SaveExamUser(ExamUser model)
{
int id = -1;
if (model != null)
{
var conf = new Configuration().Configure();
ISession session = NHibernateHelper.GetSession();
//配置NHibernate
//在Configuration中添加HbmMapping
conf.AddDeserializedMapping(NHibernateHelper.GetEntityMapping<ExamUser>(), "ExamUserXML");
//配置数据库架构元数据
SchemaMetadataUpdater.QuoteTableAndColumns(conf);
//建立SessionFactory
var factory = conf.BuildSessionFactory();
//打开Session做持久化数据
using (session = factory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
id = (int)session.Save(model);
tx.Commit();
}
}
}
return id;
}
示例6: AddNHibernateSessionFactory
public static void AddNHibernateSessionFactory(this IServiceCollection services)
{
// By default NHibernate looks for hibernate.cfg.xml
// otherwise for Web it will fallback to web.config
// we got one under wwwroot/web.config
Configuration config = new Configuration();
config.Configure();
// Auto load entity mapping class
ModelMapper mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetAssembly(typeof(Employee)).GetExportedTypes());
HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
config.AddDeserializedMapping(mapping, "NHibernate.Mapping");
SchemaMetadataUpdater.QuoteTableAndColumns(config);
// Drop & Recreate database schema
new SchemaExport(config).Drop(false, true);
new SchemaExport(config).Create(false, true);
// Register services
services.AddSingleton<ISessionFactory>(provider => config.BuildSessionFactory());
services.AddTransient<ISession>(provider => services.BuildServiceProvider().GetService<ISessionFactory>().OpenSession());
}
示例7: CargarListas
/// <summary>
/// Carga las listas de la BD que se necesitan para las consultas
/// </summary>
private void CargarListas()
{
//Iniciar sesión
var cfg = new Configuration();
cfg.Configure();
var sessions = cfg.BuildSessionFactory();
var sess = sessions.OpenSession();
//Consulta a la BD
IQuery q1 = sess.CreateQuery("FROM Cliente");
var clientesTodos = q1.List<Cliente>();
//Actualización de la lista global de clientes
clientes = clientesTodos.ToList<Cliente>();
//Consulta a la BD
IQuery q2 = sess.CreateQuery("FROM Empleada");
var empleadosTodos = q2.List<Empleada>();
//Actualización de la lista global de clientes
empleados = empleadosTodos.ToList<Empleada>();
//Carga en las tablas
sess.Close();
}
示例8: CreateStuff
private static void CreateStuff(Configuration cfg)
{
using (ISessionFactory sessionFactory = cfg.BuildSessionFactory())
using (ISession session = sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
try
{
var tempUser = new User { Username = "temp" };
session.Save(tempUser);
transaction.Commit();
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
Console.ResetColor();
transaction.Rollback();
}
finally
{
session.Close();
}
}
}
示例9: OpenSession
public static ISession OpenSession()
{
if (sessionFactory == null)
{
System.Collections.Specialized.NameValueCollection sets = System.Configuration.ConfigurationManager.AppSettings;
//获取连接字符串
string server = Utilities.GetConfigValue("server");
string pwd = VTMS.Common.Utilities.Base64Dencrypt(Utilities.GetConfigValue("DBPassword"));
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
connectionString = string.Format(connectionString, server, pwd);
try
{
Configuration cfg = new Configuration().Configure();
cfg.Proxy(p => p.ProxyFactoryFactory<NHibernate.Bytecode.DefaultProxyFactoryFactory>());
cfg.DataBaseIntegration(db =>
{
db.ConnectionString = connectionString;
});
sessionFactory = cfg.BuildSessionFactory();
}
catch (Exception e)
{
VTMS.Common.MessageUtil.ShowError("无法登陆服务器,请检查服务器IP设置是否正确,错误信息为:" + e.Message);
}
}
return sessionFactory.OpenSession();
}
示例10: MainWindow
public MainWindow()
: base(Gtk.WindowType.Toplevel)
{
Build ();
Configuration configuration = new Configuration();
configuration.Configure();
configuration.SetProperty(NHibernate.Cfg.Environment.Hbm2ddlKeyWords, "none");
configuration.AddAssembly(typeof(Categoria).Assembly);
new SchemaExport(configuration).Execute(true, false, false);
ISessionFactory sessionFactory = configuration.BuildSessionFactory();
//updateCategoria(sessionFactory);
//insertCategoria(sessionFactory);
//loadArticulo(sessionFactory);
ISession session = sessionFactory.OpenSession();
ICriteria criteria = session.CreateCriteria(typeof(Articulo));
criteria.SetFetchMode("Categoria", FetchMode.Join);
IList list = criteria.List();
foreach (Articulo articulo in list)
Console.WriteLine("Articulo Id={0} Nombre={1} Precio={2} Categoria={3}",
articulo.Id, articulo.Nombre, articulo.Precio, articulo.Categoria);
session.Close();
sessionFactory.Close();
}
示例11: Main
static void Main(string[] args)
{
var configuration = new Configuration().Configure("hibernate.cfg.xml");
//configuration.AddAssembly("HibernateTest");
var sessionFactory = configuration.BuildSessionFactory();
var session = sessionFactory.OpenSession();
var list = session.CreateCriteria<Product>().List<Product>();
foreach (var l in list)
{
Console.WriteLine("{0:3} | {1:40} | {2:4}", l.ID, l.Name, l.Quantity);
}
using(ITransaction trans = session.BeginTransaction())
{
Product product = new Product();
product.Name = "dupa";
product.Quantity = 66;
session.Save(product);
trans.Commit();
}
Console.Read();
session.Close();
}
示例12: BusinessSafeSessionFactory
public BusinessSafeSessionFactory()
{
var hibernateConfigFilePath = new NHibernateConfigPathGenerator(Database.BusinessSafe).GetConfigFilePath();
Log4NetHelper.Logger.Debug("BusinessSafeSessionFactory() - NHibernate Configuration File path: " + hibernateConfigFilePath);
var configuration = new Configuration();
configuration.Configure(hibernateConfigFilePath);
configuration.SetProperty(Environment.ConnectionStringName, "BusinessSafe");
configuration.EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[]
{
new AuditUpdateListener()
};
configuration.EventListeners.PostInsertEventListeners = new IPostInsertEventListener[]
{
new AuditUpdateListener()
};
configuration.EventListeners.PostDeleteEventListeners = new IPostDeleteEventListener[]
{
new AuditUpdateListener()
};
configuration.EventListeners.PostCollectionUpdateEventListeners = new IPostCollectionUpdateEventListener[]
{
new AuditUpdateListener()
};
_sessionFactory = configuration.BuildSessionFactory();
}
示例13: saveOrder1
public long saveOrder1()
{
ISessionFactory _sessions;
Configuration cfg = new Configuration().Configure();
_sessions = cfg.BuildSessionFactory();
TOrderData ob = new TOrderData();
ob.Configure();
TOrder od = ob.CreateOrder("test", "order.Address", "order.Phone", "order.AddText",1);
//od.Id = order.Id;
//od.Name = order.Name;
//od.OrderTime = order.OrderTime;
//od.Phone = order.Phone;
//od.Address = order.Address;
//od.AddText = order.AddText;
for (int i = 0; i < 8; i++)
{
TOrderItem oditem = new TOrderItem();
oditem.Order = od;
oditem.Price = 9.99M;
oditem.Amount = 2;
oditem.SubPrice = 19.99M;
oditem.Text = "testb" + od.Id;
oditem.DishId = 1;
oditem.DishName = "testb" + i;
od.Items.Add(oditem);
}
ob.UpdateOrder(od);
return od.Id;
}
示例14: InitMappings
/// <summary>
/// Initializes the mappings.
/// </summary>
/// <param name="config">The configuration.</param>
public static void InitMappings(Configuration config)
{
var orm = new ObjectRelationalMapper();
var mapper = new Mapper(orm);
mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && !mi.Name.EndsWith("Text"), pm => pm.Length(50));
mapper.AddPropertyPattern(mi => mi.GetPropertyOrFieldType() == typeof(string) && mi.Name.EndsWith("Text"), pm => pm.Type(NHibernateUtil.StringClob));
orm.Patterns.PoidStrategies.Add(new AssignedPoidPattern());
foreach (var componentDbInit in IoC.ResolveAllInstances<IComponentDbInit>())
{
componentDbInit.InitMappings(orm, mapper);
}
// compile the mapping for the specified entities
HbmMapping mappingDocument = mapper.CompileMappingFor(ListOfModelTypes());
// inject the mapping in NHibernate
config.AddDeserializedMapping(mappingDocument, "Domain");
// fix up the schema
SchemaMetadataUpdater.QuoteTableAndColumns(config);
SessionFactory.SessionFactoryInstance = config.BuildSessionFactory();
}
示例15: NHibernateManager
static NHibernateManager()
{
Configuration cfg= new Configuration().Configure();
//cfg.AddAssembly("App_SubCode_APAS");
//cfg.AddClass(typeof(Apas.Business.BCOtherFeeType));
//Business Persistent Entity Mappings
cfg.AddDirectory(new System.IO.DirectoryInfo
(
HttpContext.Current.Server.MapPath
(
@"~/App_Code/APAS/Business/NHibernate Mappings/"
)
)
);
//Security Layer Entity Mappings
cfg.AddDirectory(new System.IO.DirectoryInfo
(
HttpContext.Current.Server.MapPath
(
@"~/App_Code/APAS/Security/NHibernate Mappings/"
)
)
);
sessionFactory= cfg.BuildSessionFactory();
}