流畅的NHibernate?我这样做正确吗?

发布于 2024-11-01 06:36:16 字数 2925 浏览 0 评论 0原文

我是第一次使用 Fluent NHibernate 和 NHibernate。我从 2000 年左右就开始使用内部编写的自定义映射器。大约 2 年前切换到 LinqToSQL,大约 6 个月前切换到 Entities。

我想看看 Fluent/NHibernate 能提供什么。但是,我似乎无法让它正确运行。以下是我的类的副本、它们的引用、ClassMap。有人可以告诉我这个简单的实现是否正确?

这是我的映射和对象类:

using System;

using FluentNHibernate.Mapping;

namespace MyData.Data.Mappings
{
    public class Login
    {
        public virtual int LoginId { get; private set; }
        public virtual string Username { get; set; }
        public virtual User User { get; set; }
    }

    public class LoginClassMap : ClassMap<Login>
    {
        public LoginClassMap()
        {
                Table("Logins");

                Id(d => d.LoginId).GeneratedBy.Guid();
                Map(d => d.Username).Not.Nullable().Length(50);

                HasOne(d => d.User).ForeignKey("UserId").Cascade.All();
         }
    }

    public class User
    {
        public virtual Guid UserId{ get; private set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public virtual Login Login { get; set; }
    }

    public class UserClassMap : ClassMap<User>
    {
        public UserClassMap()
        {
            Table("Users");

            Id(d => d.UserId).GeneratedBy.Guid();
            Map(d => d.FirstName).Not.Nullable().Length(100);
            Map(d => d.LastName).Not.Nullable().Length(100);

            References(r => r.Login, "UserId").Not.Nullable();
        }
    }
}

这是我的存储库:

using System;
using System.Linq;

using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Linq;

using MyData.Data.Mappings;

namespace MyData.Data.Repository
{
    public class LoginRepository
    {
        private readonly ISessionFactory _sessionFactory;
        ISession _session;

        public LoginRepository()
        {
            _sessionFactory = this.CreateSessionFactory();

            _session = _sessionFactory.OpenSession();
        }

        private ISessionFactory CreateSessionFactory()
        {
            string connString = "MyDataConnectionString";


        FluentConfiguration config = Fluently.Configure()
        .Database(MsSqlConfiguration.MsSql2005.ConnectionString(
           x => x.FromConnectionStringWithKey(connString)))
        .ExposeConfiguration(
            c => c.SetProperty("current_session_context_class", "webContext"))
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Login>());

            return config.BuildSessionFactory();
        }

        public IQueryable<Login> GetAllLogins()
        {
            return _session.Linq<Login>();
        }
    }
}

每当到达 config.BuildSessionFactory() 时,它都会抛出以下错误:

创建 SessionFactory 时使用了无效或不完整的配置。

内部异常是:

调用目标已抛出异常。

这是处理这个问题的正确方法吗?任何想法或调整将不胜感激!

I am new to using Fluent NHibernate and NHibernate for the first time. I've used a custom written mapper since about 2000 that was written in house. Made a switch to LinqToSQL about 2 years ago, and about 6 months ago to Entities.

I'd like to see what Fluent/NHibernate have to offer. However, I can't seem to get it to run correctly. The following is a copy of my classes, their references, the ClassMaps. Can someone tell me if this simple implementation is correct?

This is my mappings and object classes:

using System;

using FluentNHibernate.Mapping;

namespace MyData.Data.Mappings
{
    public class Login
    {
        public virtual int LoginId { get; private set; }
        public virtual string Username { get; set; }
        public virtual User User { get; set; }
    }

    public class LoginClassMap : ClassMap<Login>
    {
        public LoginClassMap()
        {
                Table("Logins");

                Id(d => d.LoginId).GeneratedBy.Guid();
                Map(d => d.Username).Not.Nullable().Length(50);

                HasOne(d => d.User).ForeignKey("UserId").Cascade.All();
         }
    }

    public class User
    {
        public virtual Guid UserId{ get; private set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public virtual Login Login { get; set; }
    }

    public class UserClassMap : ClassMap<User>
    {
        public UserClassMap()
        {
            Table("Users");

            Id(d => d.UserId).GeneratedBy.Guid();
            Map(d => d.FirstName).Not.Nullable().Length(100);
            Map(d => d.LastName).Not.Nullable().Length(100);

            References(r => r.Login, "UserId").Not.Nullable();
        }
    }
}

This is my Repository:

using System;
using System.Linq;

using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Linq;

using MyData.Data.Mappings;

namespace MyData.Data.Repository
{
    public class LoginRepository
    {
        private readonly ISessionFactory _sessionFactory;
        ISession _session;

        public LoginRepository()
        {
            _sessionFactory = this.CreateSessionFactory();

            _session = _sessionFactory.OpenSession();
        }

        private ISessionFactory CreateSessionFactory()
        {
            string connString = "MyDataConnectionString";


        FluentConfiguration config = Fluently.Configure()
        .Database(MsSqlConfiguration.MsSql2005.ConnectionString(
           x => x.FromConnectionStringWithKey(connString)))
        .ExposeConfiguration(
            c => c.SetProperty("current_session_context_class", "webContext"))
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Login>());

            return config.BuildSessionFactory();
        }

        public IQueryable<Login> GetAllLogins()
        {
            return _session.Linq<Login>();
        }
    }
}

Whenever it gets to config.BuildSessionFactory() it throws the following error:

An invalid or incomplete configuration was used while creating a SessionFactory.

The inner Exception is:

Exception has been thrown by the target of an invocation.

Is this the correct way to approach this? Any ideas or tweaks would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

阳光下慵懒的猫 2024-11-08 06:36:16

Sean,您不能在 LoginId 上使用 GenerationBy.Guid(),因为它是一个 int。尝试使用其他生成器或更改 LoginId 的类型。

我怀疑你不能在 UserId 上使用“私有集”,因为它是 Id。

另外,HasOne(d => d.User).ForeignKey("UserId") 意味着如果您从映射中公开数据库模型,则 FK 约束的名称将为“UserId”。在我看来,您的意图是指定保存表“Users”上的 PK 的名称列。

这些链接有更多信息:

http://wiki. Fluentnhibernate.org/Fluent_mapping

http://jagregory.com/writings/i-think-you-mean-a-many-to-one-sir/

一对一流利nhibernate?

Sean, you cannot use GeneratedBy.Guid() on LoginId because it's an int. Try to use another generator or change the type of LoginId.

I suspect you cannot use "private set" on UserId because it's the Id.

Also, HasOne(d => d.User).ForeignKey("UserId") means that if you expose your database model from your mappings, the name of the FK constraint will be "UserId". It seems to me that your intention was to specify the name column that holds the PK on table "Users".

These links have more infos:

http://wiki.fluentnhibernate.org/Fluent_mapping

http://jagregory.com/writings/i-think-you-mean-a-many-to-one-sir/

one-to-one fluent nhibernate?

所有深爱都是秘密 2024-11-08 06:36:16

您似乎忘记指定代理工厂。可以这样做:

        OracleDataClientConfiguration persistenceConfigurer = OracleDataClientConfiguration
            .Oracle10
            .ConnectionString(connectionStringBuilder => connectionStringBuilder.FromAppSetting("Main.ConnectionString"))
            .ProxyFactoryFactory<ProxyFactoryFactory>()
            .CurrentSessionContext<ThreadStaticSessionContext>()
            .AdoNetBatchSize(25)
            .DoNot.ShowSql();

        FluentConfiguration cfg = Fluently.Configure()
            .Database(persistenceConfigurer)
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>());

        return cfg.BuildConfiguration();

It seems you forgot to specify proxy factory. It can be done like this:

        OracleDataClientConfiguration persistenceConfigurer = OracleDataClientConfiguration
            .Oracle10
            .ConnectionString(connectionStringBuilder => connectionStringBuilder.FromAppSetting("Main.ConnectionString"))
            .ProxyFactoryFactory<ProxyFactoryFactory>()
            .CurrentSessionContext<ThreadStaticSessionContext>()
            .AdoNetBatchSize(25)
            .DoNot.ShowSql();

        FluentConfiguration cfg = Fluently.Configure()
            .Database(persistenceConfigurer)
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>());

        return cfg.BuildConfiguration();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文