没有持久性支持:使用流畅的休眠模式保存数据时出错

时间:2019-06-24 07:50:30

标签: c# nhibernate asp.net-mvc-5 fluent-nhibernate

我正在尝试使用流畅的休眠模式将数据保存到我的数据库表中,但是它给我“没有持久性:”。我尝试了许多可用的网络解决方案,但没有任何办法可以帮助我摆脱这种局面。谁能帮助我解决我花了将近2天的时间才能找到此错误的原因,但仍然没有找到。

private static ISessionFactory InitializeSessionFactory()
{
    return Fluently.Configure().Database(MsSqlConfiguration.MsSql2012

   .ConnectionString(ConfigurationManager.ConnectionStrings["test"]
   .ConnectionString).ShowSql())
   .Mappings(m =>
    m.FluentMappings.AddFromAssemblyOf<Domain.Mapping.StatusMap>())
   .BuildSessionFactory();
}

public class StatusTypeTest
{
    public double Statusid { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public double? Createbyid { get; set; }

}

public class StatusMap : ClassMapping<StatusTypeTest>
{
    public StatusMap()
    {
        Schema("dbo");
        Table("Status");
        Lazy(false);
        Id(x => x.Statusid, map => map.Generator(Generators.Identity));

        Property(x => x.Title, map => map.Length(50));
        Property(x => x.Description, map => map.Length(250));
        Property(x => x.Createbyid, map => map.Precision(10));
    }
}



 StatusTypeTest obj= new StatusTypeTest(); 
 obj.Title = "test";
 obj.description = "My unit test";
 obj.createdBy = 1; 

 using (var session = Factory.OpenSession()) 
 { 
   using (ITransaction transaction = session.BeginTransaction())
    { 
      session.Save(obj);
      transaction.Commit(); 
    } 
  } 

1 个答案:

答案 0 :(得分:0)

g您可以在下课注册为单身人士

    public class SessionSource
    {
        private string _connectionStringProvider;
        public SessionSource(string connectionStringProvider)
        {
            _connectionStringProvider = connectionStringProvider;
        }

        public ISession GetSession()
        {
                var session = GetSessionFactory().OpenSession();
                return session;
        }

        private Configuration AssembleConfiguration(string connectionString)
        {
            return Fluently.Configure()
                    .Mappings(x => x.FluentMappings.AddFromAssemblyOf<MappingCandidate>())
                    .Database(() =>
                    {
                        return FluentNHibernate.Cfg.Db.MsSqlConfiguration
                            .MsSql2012
                            .ConnectionString(connectionString);
                    })
                    .BuildConfiguration();
        }

        private ISessionFactory GetSessionFactory()
        {
            var sessionFactory = AssembleConfiguration(_connectionStringProvider).BuildSessionFactory();
            return sessionFactory;
        }
    }

然后像使用Factory.OpenSession()一样,可以注入sessionSource并使用它

 using (var session = _sessionSource.GetSession())
 {

通过此操作,可以确保您已注册所有必需的映射。