我正在尝试在.net核心上配置NHibernate,但仍然没有成功。
我可以读取数据,但是当我尝试保存或删除时,它不起作用。
有太多的信息,比如我如何创建我的服务、存储库和映射,所以我会在这个问题中跳过一些文件,但在我的 git 存储库中一切都可用。
所以我有一个非常简单的模型。
public class Book
{
public virtual Guid Id { get; set; }
public virtual string Title { get; set; }
}
我还创建了一个扩展方法,用于在我的服务中添加 nhibernate。
public static class NHibernateExtensions
{
public static IServiceCollection AddNHibernate(this IServiceCollection services, string connectionString)
{
var mapper = new ModelMapper();
mapper.AddMappings(typeof(NHibernateExtensions).Assembly.ExportedTypes);
HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
var configuration = new Configuration()
.DataBaseIntegration(c =>
{
c.Dialect<MsSql2012Dialect>();
c.ConnectionString = connectionString;
c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
c.SchemaAction = SchemaAutoAction.Validate;
c.LogFormattedSql = true;
c.LogSqlInConsole = true;
});
configuration.AddMapping(domainMapping);
var fluentSessionFactory = Fluently
.Configure(configuration)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Book>())
.BuildSessionFactory();
var sessionFactory = configuration.BuildSessionFactory();
services.AddSingleton(fluentSessionFactory);
services.AddScoped(factory => fluentSessionFactory.OpenSession());
services.AddScoped<ISessionManager, SessionManager>();
return services;
}
}
这是我的StartUp
public void ConfigureServices(IServiceCollection services)
{
var connStr = Configuration.GetConnectionString("DefaultConnection");
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddNHibernate(connStr);
services.AddTransient<IBookRepository, BookRepository>();
services.AddTransient<IBookService, BookService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
我创建了一个用于处理简单存储库操作的BaseRepository
。
我遇到的问题是,在BaseRepository
中,当我调用Add
时,它不会保留在数据库中。
public void Delete(T entity){
using (var transaction = Session.BeginTransaction())
{
Session.Delete(entity);
transaction.Commit();
Session.Flush();
}
}
当我打电话给Queryable.ToList()
时,我得到了预期的一切。
我在数据库中不保留的配置上做错了什么?
观察:数据库是SQL Server 2017,在docker容器上运行。
这是因为您在每次访问会话时都会打开新会话:
protected ISession Session => SessionFactory.OpenSession();
事务在一个会话中启动,在第三个会话中在其他刷新中添加/删除。显然,您需要在一个会话中执行所有操作。
此外,默认情况下您不需要调用 Flush - 它应该在transaction.Commit
上自动调用。 如果你真的需要调用 Flush - 在事务提交之前这样做。