我正在尝试在.net内核上配置NHibernate,但仍然没有成功。
我可以读取数据,但当我尝试保存或删除时,它不起作用。
有太多的信息,比如我是如何创建我的服务、存储库和映射的,所以我将跳过这个问题中的一些文件,但在my git repo上一切都是可用的。
所以我有一个非常简单的模型。
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()
时,我会如期得到所有东西。
我在配置上做错了什么,它不存在于db中?
观察:数据库为SQL Server 2017,在docker容器上运行。
发布于 2019-10-05 19:03:16
这是因为您在每个Session access上打开新会话
protected ISession Session => SessionFactory.OpenSession();
事务在一个会话中启动,在另一个会话中添加/删除,在第三个会话中刷新。显然,您需要在一个会话中完成所有操作。
此外,默认情况下不需要调用Flush -它应该在transaction.Commit
上自动调用。如果你真的需要调用Flush --在事务提交之前完成。
https://stackoverflow.com/questions/58242190
复制相似问题