Ignore column using mapping by code in HNibernate

2019-08-01 10:46发布

问题:

I'm using mapping by code in NHibernate. I got a class with several properties. One of them is not related to any columns in DB but still has getter and setter.

I use ConventionModelMapper not ModelMapper. The first one assumes that all properties are mapped.

How i can tell to NHibernate to ignore it?

回答1:

Why not map the properties you want and leave the ones not needed to be mapped

check this

You can manage the persistence of ConventionModelMapper as following:

mapper.BeforeMapProperty += (mi, propertyPath, map) =>
{
    // Your code here using mi, propertyPath, and map to decide if you want to skip the property .. can check for property name and entity name if you want to ignore it
};

A better answer would be:

mapper.IsPersistentProperty((mi, declared) =>
                                             {
                                                 if (mi.DeclaringType == typeof (YourType) && mi.Name == "PropertyNameToIgnore")
                                                     return false;
                                                 return true;
                                             });


回答2:

I find it easier to just create an attribute, attach that attribute to the property, and check for it in the mapper.IsPersistentProperty method. Something like this:

class IngnoreAttribute : Attribute
{
}

class Foo
{
    [Ignore]
    public virtual string Bar { get; set; }
}

mapper.IsPersistentProperty((mi, declared) => mi.GetCustomAttribute<IgnoreAttribute>() == null);

This way, I don't have to keep a list of properties to be ignored at the mapping codes.



回答3:

If you do not mention the property that should be ignored in your NHibernate mapping, NHibernate will ignore it.