使用FluentNHibernate NHibernate 3.3进行错误的映射

时间:2013-02-26 11:26:22

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

使用“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: 

例外(更多细节):

enter image description here

例外(更多细节):

enter image description here

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。对于其他用户。

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

重要文件:

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

档案:My project download 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: 

2 个答案:

答案 0 :(得分:2)

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

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

如果您有任何问题,请与我们联系。

答案 1 :(得分:1)

根据您的背景,与NH和FNH合作起初可能会非常混乱。

但如果你替换这一行:

.FluentMappings.AddFromAssemblyOf<Person>())

这一行:

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

我相信这会解决您的问题,或至少指出您正确的方向。

此外,你应该能够消除你的PersonMappingAltertation覆盖 - 它不是必需的 - 这样一个简单的实体应该自动完成。

转到FNH Wiki Auto mapping page,详细了解自动映射。

这也会链接到sample project,我发现这是最好的入门方式。