简体   繁体   English

流畅的NHibernate:如何告诉它不要映射基类

[英]Fluent NHibernate: How to tell it not to map a base class

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. 我正在使用ASP.NET MVC和NHibernate,我所要做的就是手动映射我的实体而不映射它的基类。 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. EntityBase不应该映射的地方。

My NHibernate helper class looks like this: 我的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();
        }
    }
}

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. System.ArgumentException:类型或方法有2个通用参数,但提供了1个通用参数。 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? 有没有其他方法可以手动映射您的实体并告诉NHibernate不要映射基类?

IncludeBase<T>

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

Read more here http://wiki.fluentnhibernate.org/Auto_mapping :) 在这里阅读更多http://wiki.fluentnhibernate.org/Auto_mapping :)

If you don't want to automap a class, I would recommend using IAutoMappingOverride<T> . 如果您不想IAutoMappingOverride<T>类,我建议使用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: 假设您将这些地图集中放置,您可以将它们加载到您的autoMap:

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

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. 当你使用IgnoreBase<T>你告诉你不想将继承映射到你的数据库,但是Fluent Nhibernate仍会将你的基类映射为一个单独的类,而你却不告诉它不这样做,所以如果你想告诉Fluent Nhibnernate不要映射类本身你应该继承DefaultAutoMapConfiguration类并覆盖它的bool ShouldMap(Type type) ,如果类型是你根本不想映射它的任何类型,则返回false。

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 ) 当您使用AutoMapping通常不需要任何其他映射类或覆盖,除非您想要对映射进行更改,并且不可能使用Conventions执行此操作,或者您只想覆盖一个类的一小部分。(尽管您使用ConventionsInspectors可以做同样的事情)

您可以将IsBaseType约定用于自动化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM