Carl Hörberg
Carl Hörberg

Reputation: 6005

how to ignore a property by attribute in nhibernate

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..

Upvotes: 1

Views: 2441

Answers (4)

keithyip
keithyip

Reputation: 1035

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

Upvotes: 0

Ryan O
Ryan O

Reputation: 326

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.

Upvotes: 3

John Holliday
John Holliday

Reputation: 1308

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().

Upvotes: 0

Carl H&#246;rberg
Carl H&#246;rberg

Reputation: 6005

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.

Upvotes: 0

Related Questions