Fluent NHibernate:如何告诉它不要映射基类

发布于 2024-08-13 10:52:14 字数 3241 浏览 1 评论 0原文

在过去的两个小时里,我一直在谷歌搜索和 stackoverflowing,但找不到我的问题的答案:

我正在使用 ASP.NET MVC 和 NHibernate,我想做的就是手动映射我的实体而不映射其基础班级。我使用以下约定:

public class Car : EntityBase
{
    public virtual User User { get; set; }
    public virtual string PlateNumber { get; set; }
    public virtual string Make { get; set; }
    public virtual string Model { get; set; }
    public virtual int Year { get; set; }
    public virtual string Color { get; set; }
    public virtual string Insurer { get; set; }
    public virtual string PolicyHolder { get; set; }
}

EntityBase 不应该被映射。

我的 NHibernate 帮助程序类如下所示:

namespace Models.Repository
{
    public class NHibernateHelper
    {
        private static string connectionString;
        private static ISessionFactory sessionFactory;
        private static FluentConfiguration config;

        /// <summary>
        /// Gets a Session for NHibernate.
        /// </summary>
        /// <value>The session factory.</value>
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                {
                    // Get the connection string
                    connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
                    // Build the configuration
                    config = Fluently.Configure().Database(PostgreSQLConfiguration.PostgreSQL82.ConnectionString(connectionString));
                    // Add the mappings
                    config.Mappings(AddMappings);
                    // Build the session factory
                    sessionFactory = config.BuildSessionFactory();
                }
                return sessionFactory;
            }
        }

        /// <summary>
        /// Add the mappings.
        /// </summary>
        /// <param name="mapConfig">The map config.</param>
        private static void AddMappings(MappingConfiguration mapConfig)
        {
            // Load the assembly where the entities live
            Assembly assembly = Assembly.Load("myProject");
            mapConfig.FluentMappings.AddFromAssembly(assembly);
            // Ignore base types
            var autoMap = AutoMap.Assembly(assembly).IgnoreBase<EntityBase>().IgnoreBase<EntityBaseValidation>();
            mapConfig.AutoMappings.Add(autoMap);
            // Merge the mappings
            mapConfig.MergeMappings();
        }

        /// <summary>
        /// Opens a session creating a DB connection using the SessionFactory.
        /// </summary>
        /// <returns></returns>
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        /// <summary>
        /// Closes the NHibernate session.
        /// </summary>
        public static void CloseSession()
        {
            SessionFactory.Close();
        }
    }
}

我现在遇到的错误是:

System.ArgumentException:类型或 方法有 2 个通用参数,但是 提供了 1 个通用参数。一个 必须提供通用参数 每个通用参数

当我尝试添加映射时会发生这种情况。有没有其他方法可以手动映射实体并告诉 NHibernate 不要映射基类?

I have been googling and stackoverflowing for the last two hours and couldn't find an answer for my question:

I'm using ASP.NET MVC and NHibernate and all I'm trying to do is to manually map my entities without mapping its base class. I'm using the following convention:

public class Car : EntityBase
{
    public virtual User User { get; set; }
    public virtual string PlateNumber { get; set; }
    public virtual string Make { get; set; }
    public virtual string Model { get; set; }
    public virtual int Year { get; set; }
    public virtual string Color { get; set; }
    public virtual string Insurer { get; set; }
    public virtual string PolicyHolder { get; set; }
}

Where EntityBase SHOULD NOT be mapped.

My NHibernate helper class looks like this:

namespace Models.Repository
{
    public class NHibernateHelper
    {
        private static string connectionString;
        private static ISessionFactory sessionFactory;
        private static FluentConfiguration config;

        /// <summary>
        /// Gets a Session for NHibernate.
        /// </summary>
        /// <value>The session factory.</value>
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                {
                    // Get the connection string
                    connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
                    // Build the configuration
                    config = Fluently.Configure().Database(PostgreSQLConfiguration.PostgreSQL82.ConnectionString(connectionString));
                    // Add the mappings
                    config.Mappings(AddMappings);
                    // Build the session factory
                    sessionFactory = config.BuildSessionFactory();
                }
                return sessionFactory;
            }
        }

        /// <summary>
        /// Add the mappings.
        /// </summary>
        /// <param name="mapConfig">The map config.</param>
        private static void AddMappings(MappingConfiguration mapConfig)
        {
            // Load the assembly where the entities live
            Assembly assembly = Assembly.Load("myProject");
            mapConfig.FluentMappings.AddFromAssembly(assembly);
            // Ignore base types
            var autoMap = AutoMap.Assembly(assembly).IgnoreBase<EntityBase>().IgnoreBase<EntityBaseValidation>();
            mapConfig.AutoMappings.Add(autoMap);
            // Merge the mappings
            mapConfig.MergeMappings();
        }

        /// <summary>
        /// Opens a session creating a DB connection using the SessionFactory.
        /// </summary>
        /// <returns></returns>
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        /// <summary>
        /// Closes the NHibernate session.
        /// </summary>
        public static void CloseSession()
        {
            SessionFactory.Close();
        }
    }
}

The error that I'm getting now, is:

System.ArgumentException: The type or
method has 2 generic parameter(s), but
1 generic argument(s) were provided. A
generic argument must be provided for
each generic parameter

This happens when I try to add the mappings. Is there any other way to manually map your entities and tell NHibernate not to map a base class?

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

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

发布评论

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

评论(4

北斗星光 2024-08-20 10:52:14

IncludeBase

AutoMap.AssemblyOf<Entity>()
  .IgnoreBase<Entity>()
  .Where(t => t.Namespace == "Entities");

在此处了解更多信息 http://wiki. Fluentnhibernate.org/Auto_mapping:)

IncludeBase<T>

AutoMap.AssemblyOf<Entity>()
  .IgnoreBase<Entity>()
  .Where(t => t.Namespace == "Entities");

Read more here http://wiki.fluentnhibernate.org/Auto_mapping :)

明月松间行 2024-08-20 10:52:14

如果您不想自动映射类,我建议使用 IAutoMappingOverride。我不关心你的数据库,但它可能看起来像:

public class CarOverride : IAutoMappingOverride<Car>
{

    public void Override(AutoMapping<Car> mapping){
        mapping.Id( x => x.Id, "CarId")
          .UnsavedValue(0)
          .GeneratedBy.Identity();


        mapping.References(x => x.User, "UserId").Not.Nullable();

        mapping.Map(x => x.PlateNumber, "PlateNumber");
        // other properties
    }
}

假设你将这些地图集中放置,然后你可以将它们加载到你的 autoMap 上:

var autoMap = AutoMap.Assembly(assembly).IgnoreBase<EntityBase>().IgnoreBase<EntityBaseValidation>()
                .UseOverridesFromAssemblyOf<CarOverride>();

If you don't want to automap a class, I would recommend using IAutoMappingOverride<T>. I don't about your database, but it might look like:

public class CarOverride : IAutoMappingOverride<Car>
{

    public void Override(AutoMapping<Car> mapping){
        mapping.Id( x => x.Id, "CarId")
          .UnsavedValue(0)
          .GeneratedBy.Identity();


        mapping.References(x => x.User, "UserId").Not.Nullable();

        mapping.Map(x => x.PlateNumber, "PlateNumber");
        // other properties
    }
}

Assuming you keep these maps centrally located, you could then load them on your autoMap:

var autoMap = AutoMap.Assembly(assembly).IgnoreBase<EntityBase>().IgnoreBase<EntityBaseValidation>()
                .UseOverridesFromAssemblyOf<CarOverride>();
你爱我像她 2024-08-20 10:52:14

我知道这是一个老问题,但我认为这里缺少一些东西:

当您使用 IgnoreBase 时,您是在告诉您不想将继承映射到数据库中,而是 Fluent Nhibernate 仍然会将您的基类映射为单独的类,而您不告诉它不要这样做,因此如果您想告诉 Fluent Nhibnernate 不要映射类本身,您应该继承 DefaultAutoMapConfiguration 类并覆盖其 bool ShouldMap(Type type) ,如果该类型是您根本不想映射的任何类型,则返回 false。

当您使用AutoMapping时,通常您不需要任何其他映射类或覆盖,除非您想在映射中进行更改,并且使用Conventions不可能做到这一点,或者您只是想覆盖一个类的一小部分。(尽管您可以使用 ConventionsInspectors 执行相同的操作)

I know it's an old question but I think that some things are missing here :

When you use IgnoreBase<T> you are telling that you don't want to map inheritance into your database but Fluent Nhibernate will still map your base class as an individual class while you don't tell it not to do that, so if you want to tell Fluent Nhibnernate not to map the class itself you should inherit DefaultAutoMapConfiguration class and override its bool ShouldMap(Type type) and return false if the type is any type that you don't want to map it at all.

When you use AutoMapping generally you don't need any other mapping classes or overrides unless you want to make a change in your mappings and it's not possible doing that using Conventions or you just want to override a small part of one class.(Although you can do the same using Conventions and Inspectors)

浊酒尽余欢 2024-08-20 10:52:14

您可以使用 IsBaseType 约定进行自动映射

You can use IsBaseType convention for your automappings

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