开发者

Ignore column using mapping by code in HNibernate

开发者 https://www.devze.com 2023-04-10 14:37 出处:网络
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'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 ass开发者_如何学Goumes that all properties are mapped.

How i can tell to NHibernate to ignore it?


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.


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;
                                             });


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号