7

I have an interface named IEntity which till now has one concrete class named Entity, this interface has a read only property. I'd rather to map the interface,but because an interface cant have a private field,i cant use option camelcase field with prefix option to map it,so what can I do?

public interface IEntity 
{public readonly string Name{get;} }

public class Entity:IEntity
{public readonly string Name{get;}}

public class EntityMap:ClassMap<IEntityMap>
{
  //how to map the readonly property
}
Adrakadabra
  • 591
  • 2
  • 12
  • 23
  • 3
    `public readonly string Name{get;}` I don't think this is valid C#. Fields can be marked `readonly`. Properties are readonly by simply having no setter. And interface members have no visibility specifier. – CodesInChaos Jun 12 '11 at 17:01
  • Public getter and Protected setter should allow NH to map successfully, I believe. – Sergey Akopov Jun 12 '11 at 17:05

3 Answers3

16

Try:

<property name="Name" type="string" access="readonly"/>

NHibernate Read Only Property Mapping

and if you use Fluent:

Mapping a read-only property with no setter using Fluent NHibernate

I think this can be useful too:

How to map an interface in nhibernate?

updated

I think a first step is correct your code. Then try to post your mapping file or fluent configuration. We cannot help you if it is not clear what you want to achieve.

Community
  • 1
  • 1
danyolgiax
  • 12,798
  • 10
  • 65
  • 116
  • the problem is that some how i want to set this property , but because I cant use private field ,i am not able to set the private one instead of public one – Adrakadabra Jun 12 '11 at 17:14
2

You map classes in NHibernate not interfaces. As others have pointed out, you are confusing the readonly keyword with a read-only property: the readonly keyword means that the field can only be set in the constructor. A read-only property has no or a private setter.

But I think you can achieve what you want using this:

public interface IEntity 
{
    string Name { get; } 
}

public class Entity : IEntity
{
    public string Name { get; private set; }
}

public class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Map(x => x.Name);
    }
}

NHibernate uses reflection so it is able to set the Name property, but it is read-only in your application.

Tri Q Tran
  • 5,500
  • 2
  • 37
  • 58
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
1

You can set ReadOnly property in ClassMap configuration.

public interface IEntity 
{
    string Name { get; } 
}

public class Entity : IEntity
{
    public string Name { get; }
}

public class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Map(x => x.Name).Access.ReadOnly();
    }
}
Rafael Pizao
  • 742
  • 8
  • 21