2

使用“FluentNHibernate”时出现错误。.xml 中的类似文件工作正常,但我想使用“FluentNHibernate”更容易。你知道我哪里出错了吗?以及如何解决这个问题?

复制例外

NHibernate.MappingException was unhandled by user code
  Message=No persister for: TreningToWork.Models.Person
  Source=NHibernate
  StackTrace:
       at NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
       at NHibernate.Impl.SessionImpl.GetEntityPersister(String entityName, Object obj)
       at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
       at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
       at NHibernate.Event.Default.DefaultSaveEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
       at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
       at NHibernate.Event.Default.DefaultSaveEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event)
       at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
       at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event)
       at NHibernate.Impl.SessionImpl.Save(Object obj)
       at NHibernateTutorial.PersonRepository.Add(Person newPerson) in D:\praca\TreningToWork\TreningToWork\Repository\PersonRepository.cs:line 15
       at TreningToWork.Controllers.ShowDataController.Index() in D:\praca\TreningToWork\TreningToWork\Controllers\ShowDataController.cs:line 21
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException: 

例外(更多细节):

在此处输入图像描述

例外(更多细节):

在此处输入图像描述

FluentNHibernate(使其与 .xml 相同)

using System.ComponentModel.DataAnnotations;
using FluentNHibernate.Automapping;
using FluentNHibernate.Automapping.Alterations;

namespace TreningToWork.Models
{
    public class Person 
    {
        [Key]
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Surname { get; set; }
    }
    public class PersonMappingAltertation : IAutoMappingOverride<Person>
    {
        public void Override(AutoMapping<Person> mapping)
        {
            mapping.Table("Person");
            mapping.Id(x => x.Id, "Id").GeneratedBy.Identity();
            mapping.Map(x=> x.Name, "Name").Column("Name").Not.Nullable();
            mapping.Map(x => x.Surname, "Surname").Column("Surname").Not.Nullable();
        }
    }
}

人员助手

using NHibernate;
using NHibernate.Cfg;
using TreningToWork.Models;

namespace TreningToWork.ModelsHelper
{
    public class PersonHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    var configuration = new Configuration();
                    configuration.Configure();
                    configuration.AddAssembly(typeof(Person).Assembly);
                    _sessionFactory = configuration.BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}

个人资料库

using NHibernate;
using TreningToWork.Models;
using TreningToWork.ModelsHelper;

namespace NHibernateTutorial
{
    public class PersonRepository
    {
        public void Add(Person newPerson)
        {
            using (ISession session = PersonHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(newPerson);
                    transaction.Commit();
                }
            }
        }

        public Person GetPersonByName(string name)
        {
            using (ISession session = PersonHelper.OpenSession())
            {
                var result = session.QueryOver<Person>().Where(x => x.Name == name).SingleOrDefault();
                return result ?? new Person();
            }
        }

        public void Update(Person newPerson)
        {
            using (ISession session = PersonHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Update(newPerson);
                    transaction.Commit();
                }
            }
        }

        public void Delete(Person newPerson)
        {
            using (ISession session = PersonHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(newPerson);
                    transaction.Commit();
                }
            }
        }

    }
}

编辑文件错误

System.ArgumentNullException was unhandled by user code
  Message=Value cannot be null.
Parameter name: Data Source
  Source=System.Data
  ParamName=Data Source
  StackTrace:
       at System.Data.SqlClient.SqlConnectionStringBuilder.set_DataSource(String value)
       at FluentNHibernate.Cfg.Db.MsSqlConnectionStringBuilder.Create()
       at FluentNHibernate.Cfg.Db.PersistenceConfiguration`2.CreateProperties()
       at FluentNHibernate.Cfg.Db.PersistenceConfiguration`2.ConfigureProperties(Configuration nhibernateConfig)
       at FluentNHibernate.Cfg.FluentConfiguration.Database(IPersistenceConfigurer config)
       at TreningToWork.ModelsHelper.PersonHelper.get_SessionFactory() in D:\praca\TreningToWork\TreningToWork\ModelsHelper\PersonHelper.cs:line 20
       at TreningToWork.ModelsHelper.PersonHelper.OpenSession() in D:\praca\TreningToWork\TreningToWork\ModelsHelper\PersonHelper.cs:line 40
       at NHibernateTutorial.PersonRepository.Add(Person newPerson) in D:\praca\TreningToWork\TreningToWork\Repository\PersonRepository.cs:line 11
       at TreningToWork.Controllers.ShowDataController.Index() in D:\praca\TreningToWork\TreningToWork\Controllers\ShowDataController.cs:line 21
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException: 

我改变的工厂

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using TreningToWork.Models;

namespace TreningToWork.ModelsHelper
{
    public class PersonHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    _sessionFactory = Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2008
                    .ConnectionString(c => c
                    .FromAppSetting("rafalConnectionString"))
                        //<%$ ConnectionStrings:rafalConnectionString %>
                    .ShowSql())
                    .Mappings(m => m
                    .FluentMappings.AddFromAssemblyOf<Person>())
                    .BuildSessionFactory();
                    // var configuration = new Configuration();
                    // configuration.Configure();
                    // configuration.AddAssembly(typeof(Person).Assembly);
                    // _sessionFactory = configuration.BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}

真的,我在配置方面遇到了问题。我将我的项目添加到这篇文章中。告诉我我在哪里犯了错误以及如何解决这个问题。我没有找到很好的例子,这个项目可能会在将来完成时转到 youtube。对于其他用户。

如果您了解这篇文章中的所有文件,则不必上传我的项目。

重要文件:

Controller -> 有控制器 Models、ModelsHelper、Repository 和 View。如果您打开网站,我的软件必须将新表和数据放入数据库。现在我遇到了这个问题。当我使用 .xml 文件时,一切正常,但我想使用“FluentNHibernate”,这是一个问题。

文件:我的项目下载 praca.zip

下一个错误:

System.ArgumentNullException was unhandled by user code
  Message=Value cannot be null.
Parameter name: Data Source
  Source=System.Data
  ParamName=Data Source
  StackTrace:
       at System.Data.SqlClient.SqlConnectionStringBuilder.set_DataSource(String value)
       at FluentNHibernate.Cfg.Db.MsSqlConnectionStringBuilder.Create()
       at FluentNHibernate.Cfg.Db.PersistenceConfiguration`2.CreateProperties()
       at FluentNHibernate.Cfg.Db.PersistenceConfiguration`2.ConfigureProperties(Configuration nhibernateConfig)
       at FluentNHibernate.Cfg.FluentConfiguration.Database(IPersistenceConfigurer config)
       at TreningToWork.ModelsHelper.PersonHelper.get_SessionFactory() in D:\praca\TreningToWork\TreningToWork\ModelsHelper\PersonHelper.cs:line 21
       at TreningToWork.ModelsHelper.PersonHelper.OpenSession() in D:\praca\TreningToWork\TreningToWork\ModelsHelper\PersonHelper.cs:line 50
       at NHibernateTutorial.PersonRepository.Add(Person newPerson) in D:\praca\TreningToWork\TreningToWork\Repository\PersonRepository.cs:line 11
       at TreningToWork.Controllers.ShowDataController.Index() in D:\praca\TreningToWork\TreningToWork\Controllers\ShowDataController.cs:line 21
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException: 
4

2 回答 2

2

你的项目的问题太多了,无法一一列举。我做了很多更改(主要是删除了不必要的代码),让它工作并上传到http://www.sendspace.pl/en/file/8f7f2ebf8fabf912800d64c

关键的变化是使用 Ninject 依赖注入框架将会话工厂创建为单例和每个请求的会话。

如果您有任何问题,请告诉我。

于 2013-03-06T05:00:25.820 回答
1

根据您的背景,一开始使用 NH 和 FNH 可能会非常混乱。

但是如果你替换这一行:

.FluentMappings.AddFromAssemblyOf<Person>())

用这条线:

.AutoMappings.Add(AutoMap.AssemblyOf<Person>())

我相信这将解决您的问题,或者至少为您指明正确的方向。

此外,您应该能够消除您的 PersonMappingAltertation 覆盖 - 它不是必需的 - 这样一个简单的实体应该可以很好地自动映射。

转到FNH Wiki 自动映射页面以获得对自动映射的良好概述。

这也将链接到一个示例项目,我发现这是最好的入门方式。

于 2013-02-28T20:37:58.297 回答