[英]What does NHibernate.AssertionFailure on doing transaction.Commit() mean?
[英]NHibernate don't persists with session.Save and transaction.Commit
我正在尝试在 .net 内核上配置 NHibernate 但仍然没有成功。
我可以读取数据,但是当我尝试保存或删除时,它不起作用。
有太多信息,比如我如何创建我的服务、存储库和映射,所以我将跳过这个问题中的一些文件,但一切都可以在我的 git repo中找到。
所以我有一个非常简单的model。
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 容器上运行。
那是因为您在每个Session 访问中打开了新的 session :
protected ISession Session => SessionFactory.OpenSession();
事务在一个 session 添加/删除在第三个其他刷新中开始。 显然,您需要在一个 session 中完成所有操作。
此外,您不需要默认调用 Flush - 它应该在transaction.Commit
上自动调用。 如果你真的需要调用 Flush - 在事务提交之前做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.