开发者

how to ignore a property by attribute in nhibernate

开发者 https://www.devze.com 2022-12-16 02:20 出处:网络
How can i ignore a property by decorating a property with an attribute? the base class AttributePropertyConvention doesn\'t seems to have that ability, or can it? Doesn\'开发者_如何学编程t find anythi

How can i ignore a property by decorating a property with an attribute? the base class AttributePropertyConvention doesn't seems to have that ability, or can it? Doesn'开发者_如何学编程t find anything sutiable on IPropertyInstance to set..


I tried creating a convention with either of the two suggestions and even both and none seemed to work with fluent nhibernate 1.3.0.727

public class IgnoreAttributeConvention : AttributePropertyConvention<IgnoreAttribute>
{
    protected override void Apply(IgnoreAttribute attribute, IPropertyInstance instance)
    {
        instance.ReadOnly();
    }
}


public class IgnoreAttributeConvention : AttributePropertyConvention<IgnoreAttribute>
{
    protected override void Apply(IgnoreAttribute attribute, IPropertyInstance instance)
    {
        instance.Access.None();
    }
}

public class IgnoreAttributeConvention : AttributePropertyConvention<IgnoreAttribute>
{
    protected override void Apply(IgnoreAttribute attribute, IPropertyInstance instance)
    {
        instance.Access.None();
        instance.ReadOnly();
    }
}

I later found this google groups discussion which although older states you cannot ignore properties with convention, it must be done by overriding the class map if using automapping.

https://groups.google.com/forum/?fromgroups#!topic/fluent-nhibernate/PDOBNzdJcc4

That is old and I don't know if it is still relevant but that was my experience. I hope this saves someone else the trouble of attempting to use this solution or spurs someone else to point out where I might be going wrong.


it was very easy:

public class IgnoreAttributeConvention : AttributePropertyConvention<IgnoreAttribute>
{
    protected override void Apply(IgnoreAttribute attribute, IPropertyInstance instance)
    {
        instance.ReadOnly();
    }
}

where IgnoreAttribute is a simple/empty attribute.


The instance.ReadOnly() method tells FNH to not look for changes on the property in the database. To ignore the property altogether you need to call instance.Access.None().


The following code will prevent a column from generated in your database.

public class MyEntity
{
    [NotMapped]
    public bool A => true;
}

public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        if (member.MemberInfo.GetCustomAttributes(typeof(NotMappedAttribute), true).Length > 0)
        {
            return false;
        }
        return base.ShouldMap(member);
    }
}
0

精彩评论

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

关注公众号