Fluent:具有无效的子元素“多对一”在命名空间中

发布于 2024-09-18 05:18:29 字数 3763 浏览 3 评论 0原文

我正在尝试通过 Fluent NHibernate 映射我现有的数据库,但出现错误:

The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'many-to-one' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'meta, subselect, cache, synchronize, comment, tuplizer, id, composite-id' in namespace 'urn:nhibernate-mapping-2.2'."}

我是 Fluent 新手,我不知道如何修复它? (也许是因为 id 是字符串?)

这是我的模型类:

namespace Server.Model
{
    public partial class User
    {
        string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        string _email;

        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }
        TypeOfUser _typeOfUser;

        public TypeOfUser TypeOfUser
        {
            get { return _typeOfUser; }
            set { _typeOfUser = value; }
        }
        string _idUser;

        public string IdUser
        {
            get { return _idUser; }
            set { _idUser = value; }
        }

        public string Password { get; set; }

        public static void AddUserTest()
        {
            var sessionFactory = BuildSessionFactory();

            using (ISession session = sessionFactory.OpenSession())
            {

                using (ITransaction transaction = session.BeginTransaction())
                {

                    session.Save(new User()
                                     {
                                         _idUser = "adapol",
                                         _name = "Adam Mickiewicz",
                                         _email = "[email protected]",
                                         _typeOfUser = Model.TypeOfUser.NormalUser
                                     });
                }
            }
        }

        private static ISessionFactory BuildSessionFactory()
        {
            AutoPersistenceModel model = CreateMappings();

            return Fluently.Configure().Database(MsSqlConfiguration.MsSql2005
  .ConnectionString(c => c.FromConnectionStringWithKey("gwd"))).Mappings(m => m.AutoMappings.Add(model))
    .ExposeConfiguration((Configuration config) => new SchemaExport(config).Create(false, true)).BuildSessionFactory();

        }

        private static AutoPersistenceModel CreateMappings()
        {
            return AutoMap
                .Assembly(System.Reflection.Assembly.GetCallingAssembly())
                .Where(t => t.Namespace == "Server.Mappings");
        }


    }
}

我只有一个 classMap

namespace Server.Mappings
{
    public class UserMap : ClassMap<User>
    {
        public UserMap()
        {
            Table("Users");

            Id(x => x.IdUser,"IdUser");
            Map(x => x.Email);
            Map(x => x.Name);
            Map(x => x.Password);
            Map(x => x.TypeOfUser,"Type");
        }
    }
}

这是创建我的表的脚本(它已经存在):

USE [GWD]
GO
/****** Object:  Table [dbo].[Users]    Script Date: 09/02/2010 23:08:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
    [IDuser] [nvarchar](50) NOT NULL,
    [Type] [int] NOT NULL,
    [Name] [nvarchar](max) NOT NULL,
    [Email] [nvarchar](50) NOT NULL,
    [Password] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
    [IDuser] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

I'm trying to map myexisting database by Fluent NHibernate I get error:

The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'many-to-one' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'meta, subselect, cache, synchronize, comment, tuplizer, id, composite-id' in namespace 'urn:nhibernate-mapping-2.2'."}

I'm newbie in Fluent and I don't know how to fix it ? (maybe it is because id is string ?)

Here is my model class:

namespace Server.Model
{
    public partial class User
    {
        string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        string _email;

        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }
        TypeOfUser _typeOfUser;

        public TypeOfUser TypeOfUser
        {
            get { return _typeOfUser; }
            set { _typeOfUser = value; }
        }
        string _idUser;

        public string IdUser
        {
            get { return _idUser; }
            set { _idUser = value; }
        }

        public string Password { get; set; }

        public static void AddUserTest()
        {
            var sessionFactory = BuildSessionFactory();

            using (ISession session = sessionFactory.OpenSession())
            {

                using (ITransaction transaction = session.BeginTransaction())
                {

                    session.Save(new User()
                                     {
                                         _idUser = "adapol",
                                         _name = "Adam Mickiewicz",
                                         _email = "[email protected]",
                                         _typeOfUser = Model.TypeOfUser.NormalUser
                                     });
                }
            }
        }

        private static ISessionFactory BuildSessionFactory()
        {
            AutoPersistenceModel model = CreateMappings();

            return Fluently.Configure().Database(MsSqlConfiguration.MsSql2005
  .ConnectionString(c => c.FromConnectionStringWithKey("gwd"))).Mappings(m => m.AutoMappings.Add(model))
    .ExposeConfiguration((Configuration config) => new SchemaExport(config).Create(false, true)).BuildSessionFactory();

        }

        private static AutoPersistenceModel CreateMappings()
        {
            return AutoMap
                .Assembly(System.Reflection.Assembly.GetCallingAssembly())
                .Where(t => t.Namespace == "Server.Mappings");
        }


    }
}

I have only one classMap

namespace Server.Mappings
{
    public class UserMap : ClassMap<User>
    {
        public UserMap()
        {
            Table("Users");

            Id(x => x.IdUser,"IdUser");
            Map(x => x.Email);
            Map(x => x.Name);
            Map(x => x.Password);
            Map(x => x.TypeOfUser,"Type");
        }
    }
}

This is script to create my table( it already exists):

USE [GWD]
GO
/****** Object:  Table [dbo].[Users]    Script Date: 09/02/2010 23:08:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
    [IDuser] [nvarchar](50) NOT NULL,
    [Type] [int] NOT NULL,
    [Name] [nvarchar](max) NOT NULL,
    [Email] [nvarchar](50) NOT NULL,
    [Password] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
    [IDuser] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

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

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

发布评论

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

评论(3

纵山崖 2024-09-25 05:18:29

不要依赖自动映射:

private static ISessionFactory BuildSessionFactory()
        {
            AutoPersistenceModel model = CreateMappings();

            return Fluently.Configure().Database(MsSqlConfiguration.MsSql2005
  .ConnectionString(c => c.FromConnectionStringWithKey("gwd"))).Mappings(m => m.AutoMappings.Add(model))
    .ExposeConfiguration((Configuration config) => new SchemaExport(config).Create(false, true)).BuildSessionFactory();

        }

试试这个:

private static ISessionFactory BuildSessionFactory()
{
    return Fluently
        .Configure()
        .Database(
            MsSqlConfiguration
                .MsSql2005
                .ConnectionString(c => c.FromConnectionStringWithKey("gwd"))
         )
         .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>())
         .ExposeConfiguration(config => new SchemaExport(config).Create(false, true))
         .BuildSessionFactory();
}

您可能还需要将 User 属性设为虚拟。


这是一个使用 SQLite 的完整工作示例,我用它来说明示例配置:

public class User
{
    public virtual string IdUser { get; set; }
    public virtual string Name { get; set; }
    public virtual string Email { get; set; }
    public virtual string Password { get; set; }
}

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("Users");
        Id(x => x.IdUser);
        Map(x => x.Email);
        Map(x => x.Name);
        Map(x => x.Password);
    }
}


class Program
{
    static void Main(string[] args)
    {
        if (File.Exists("data.db3"))
        {
            File.Delete("data.db3");
        }

        using (var factory = CreateSessionFactory())
        {
            using (var connection = factory.OpenSession().Connection)
            {
                ExecuteQuery("create table Users(IdUser string primary key, Name string, Email string, Password string)", connection);
            }

            using (var session = factory.OpenSession())
            using (var tx = session.BeginTransaction())
            {
                session.Save(new User()
                {
                    IdUser = "adapol",
                    Name = "Adam Mickiewicz",
                    Email = "[email protected]",
                });
                tx.Commit();
            }
        }
    }

    private static ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure()
            .Database(
                SQLiteConfiguration.Standard.UsingFile("data.db3").ShowSql()
            )
            .Mappings(
                m => m.FluentMappings.AddFromAssemblyOf<UserMap>()
            )
            .BuildSessionFactory();
    }

    static void ExecuteQuery(string sql, IDbConnection connection)
    {
        using (var command = connection.CreateCommand())
        {
            command.CommandText = sql;
            command.ExecuteNonQuery();
        }
    }
}

Instead of relying on automappings:

private static ISessionFactory BuildSessionFactory()
        {
            AutoPersistenceModel model = CreateMappings();

            return Fluently.Configure().Database(MsSqlConfiguration.MsSql2005
  .ConnectionString(c => c.FromConnectionStringWithKey("gwd"))).Mappings(m => m.AutoMappings.Add(model))
    .ExposeConfiguration((Configuration config) => new SchemaExport(config).Create(false, true)).BuildSessionFactory();

        }

Try this:

private static ISessionFactory BuildSessionFactory()
{
    return Fluently
        .Configure()
        .Database(
            MsSqlConfiguration
                .MsSql2005
                .ConnectionString(c => c.FromConnectionStringWithKey("gwd"))
         )
         .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>())
         .ExposeConfiguration(config => new SchemaExport(config).Create(false, true))
         .BuildSessionFactory();
}

Also you might need to make the User properties virtual.


And here's a full working example using SQLite that I've put to illustrate sample configuration:

public class User
{
    public virtual string IdUser { get; set; }
    public virtual string Name { get; set; }
    public virtual string Email { get; set; }
    public virtual string Password { get; set; }
}

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("Users");
        Id(x => x.IdUser);
        Map(x => x.Email);
        Map(x => x.Name);
        Map(x => x.Password);
    }
}


class Program
{
    static void Main(string[] args)
    {
        if (File.Exists("data.db3"))
        {
            File.Delete("data.db3");
        }

        using (var factory = CreateSessionFactory())
        {
            using (var connection = factory.OpenSession().Connection)
            {
                ExecuteQuery("create table Users(IdUser string primary key, Name string, Email string, Password string)", connection);
            }

            using (var session = factory.OpenSession())
            using (var tx = session.BeginTransaction())
            {
                session.Save(new User()
                {
                    IdUser = "adapol",
                    Name = "Adam Mickiewicz",
                    Email = "[email protected]",
                });
                tx.Commit();
            }
        }
    }

    private static ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure()
            .Database(
                SQLiteConfiguration.Standard.UsingFile("data.db3").ShowSql()
            )
            .Mappings(
                m => m.FluentMappings.AddFromAssemblyOf<UserMap>()
            )
            .BuildSessionFactory();
    }

    static void ExecuteQuery(string sql, IDbConnection connection)
    {
        using (var command = connection.CreateCommand())
        {
            command.CommandText = sql;
            command.ExecuteNonQuery();
        }
    }
}
玩物 2024-09-25 05:18:29

我的猜测是,您正在尝试使用 AutoMapping,但您将自动映射器指向您的映射命名空间而不是您的模型。这会导致 FNH 尝试自动映射您的实际映射类。
您可以将 AutoMap 指向您的模型名称空间,但查看您的代码可能会遇到更多困难。
在这个阶段,使用普通的非自动映射器可能会更好。

My guess is that you are trying to use AutoMapping but you are pointing the auto-mapper at your mapping namespace not your model. This results in FNH trying to automap your actual mapping classes.
You could point AutoMap at your model namespace, but looking at your code you may run into more difficulties.
It's probably better at this stage to use the normal, non-auto mapper.

信愁 2024-09-25 05:18:29

我猜您正在运行 Fluent NHibernate 的过时版本;如果您运行的是 1.1,您会得到一个更有用的异常。 90% 的情况下,当您的类没有映射 Id 时,您(过去)会遇到该异常。

我相当确定自动映射器没有找到您的 Id 属性。首先,你会得到这个例外;其次,您的 ClassMap 显示您正在使用名为 IdUser 的属性作为该实体中的 Id;第三,自动映射器默认配置为仅搜索名为 Id 的属性。

我建议您阅读自动映射维基页面,因为它涵盖了所有这些内容。

I'm guessing you're running an out-of-date version of Fluent NHibernate; if you were running 1.1, you would get a more helpful exception. 90% of the time you (used to) get that exception when your class doesn't have an Id mapped.

I'm fairly sure the automapper isn't finding your Id properties. First, you're getting that exception; second, your ClassMap shows you're using a property named IdUser as the Id in that entity; third, the automapper is configured by default to search for properties called Id only.

I suggest you read the automapping wiki page, as it covers all these things.

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