How to set entire mapping to read only in NHibernate 3.2 mapping-by-code? - nhibernate-mapping

I'm just getting up to speed with NHibernate 3.2 and its "mapping by code" feature, and migrating our Fluent mapping over to it.
Is there an equivalent of the fluent "ReadOnly();" function, to make the entire mapping read only?
Thanks in advance.

Use Mutable(false) in the mapping.
Read this post for corresponding hbm file mapping from where I could infer this.
http://davybrion.com/blog/2007/08/read-only-data-in-nhibernate/

Use PropertyMapper action to define access style:
public class EntityMapping : ClassMapping<Entity>
{
public EntityMapping()
{
Id(m => m.Id, map => map.Generator(Generators.HighLow));
Property(m => m.Name, map => map.Access(Accessor.ReadOnly));
}
}

For those looking for this in fluent you are looking for ReadOnly() as below:
public class FooMap : ClassMap<Foo> {
public FooMap() {
Schema("bar");
Table("foo");
LazyLoad();
ReadOnly();
CompositeId()
.KeyProperty(x => x.ID, "ID")
.KeyProperty(x => x.Year, "Year");
Map(x => x.FirstField).Column("FirstField").Length(1);
}
}

Related

Unable to resolve property: Id

I'm getting the following error message:
NHibernate.HibernateException: NHibernate.HibernateException: Unable to resolve property: Id.
This error is thrown from the following line of code:
User userFound = session.QueryOver<User>()
.Where(x => x.Id == testObjects.TestUser.Id)
.SingleOrDefault();
My abbreviated mappings are as follows:
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("USER_HEADER");
Id(x => x.Id, "USER_ID")
.GeneratedBy.Foreign("UserLocation");
HasOne(x => x.UserLocation)
.PropertyRef(x => x.Id)
.Cascade.All();
}
}
public class LocationMap : ClassMap<Location>
{
public LocationMap()
{
Table("LOC_HEADER");
Id(x => x.Id, "LOC_ID");
HasOne(x => x.User)
.PropertyRef(x => x.Id);
}
}
I was able to query a User object before I added this relationship to Location so I know it has something to do with it but I'm not sure what exactly. I can successfully create a User object that is tied to a Location but cannot query it. Using ISession.Get produces the same error as the above QueryOver statement.
Below is the overall unit test I am running that is failing:
public void Can_Create_User()
{
using (NHibernate.ISession session = SessionFactory.GetCurrentSession())
{
using (NHibernate.ITransaction tran = session.BeginTransaction())
{
session.Save(testObjects.TestValidationDetail);
session.Save(testObjects.TestUser);
tran.Commit();
}
}
using (NHibernate.ISession session = SessionFactory.GetCurrentSession())
{
User userFound = session.QueryOver<User>().Where(x => x.Id == testObjects.TestUser.Id).SingleOrDefault();
Assert.IsNotNull(userFound);
Assert.AreEqual(userFound.Id, userFound.UserLocation.Id);
}
}
It turns out this was caused by me incorrectly using PropertyRef. In my instance I did not need to use this. The error was being generated because there was no property named Id but there was an ID named Id. I corrected my issues by changing my mappings to:
HasOne(x => x.UserLocation)
.PropertyRef(x => x.Id)
.Cascade.All();
to
HasOne(x => x.UserLocation)
.Cascade.All();
and
HasOne(x => x.User)
.PropertyRef(x => x.Id);
to
HasOne(x => x.User)
PropertyRef maps to property-ref is a legacy feature, it is meant to allow you to create many-to-one associations when the association is not done on the primary key of the association.
I am guessing you want to specify on what property the join is to be made and that is why you used PropertyRef.. if you are using Nhibernates default convention in the mapping for the Id of UserLocation you dont need to explicitly specify the property.. if you are explicitly giving the column name then you need to do the same here, but in that case you need to specify the exact same column name.
Hope that helps..

Fluent NHibernate : Conventions / KeyColumn

Below the code, a Customer can have several address. There is a one-to-many relation. I'd like in the Address table as FK a field named "Customer" and not "Customer_id"
I' tried to add :
.KeyColumn("Customer") > no change
I tried to use to change ForeignKeyConvention no change.
Any idea ?
public class CustomerMap : ClassMap<Customer>
{
protected CustomerMap()
{
Id(x => x.Id).Not.Nullable();
Map(x => x.FirstName).Not.Nullable().Length(25);
Map(x => x.LastName);
HasMany<Address>(x => x.Addresses)
.KeyColumn("Customer")
.AsSet()
.Inverse()
.Cascade.AllDeleteOrphan();
}
}
public class AddressMap : ClassMap<Address>
{
public AddressMap()
{
Id(x => x.Id);
Map(x => x.City).Not.Nullable().Length(100);
}
}
public class ForeignKeyReferenceConvention : IHasManyConvention
{
public void Apply(IOneToManyCollectionInstance instance)
{
instance.Key.PropertyRef("EntityId");
}
}
public void DBCreation()
{
FluentConfiguration config = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString("...."))
.Mappings(m =>
m.AutoMappings
.Add(AutoMap.AssemblyOf<Customer>())
.Add(AutoMap.AssemblyOf<Address>()
.Conventions.Setup(c => c.Add<ForeignKeyReferenceConvention>())
)
);
config.ExposeConfiguration(
c => new SchemaExport(c).Execute(true, true, false))
.BuildConfiguration();
}
I've never used automapping myself, but isn't ClassMap only used with "default" fluent mapping (not automapping)? Do you want to use fluent mapping or auto mapping?
Why is your one-to-many inverse although you don't have a many-to-one side mapped?
Btw, what's the purpose of that convention? PropertyRef() shouldn't be used unless absolutely needed (NHibernate can't do some optimizations with that).

Fluent nHibernate Mapping issue

I have a DB with the following tables
Users
Roles
UserInRoles (Bridge table for Users and Roles for many to many relationship
Modules
ModulePermission (this include the PK of Roles and modules and a bool field to identify the role has permission to access the module or not
now i m confuse about the Mapping of these table in fluent nHibernate, i did the mapping as define in Fluent nHibernate Wiki site but getting this error:
(XmlDocument)(3,6): XML validation
error: The element 'composite-id' in
namespace 'urn:nhibernate-mapping-2.2'
has incomplete content. List of
possible elements expected: 'meta,
key-property, key-many-to-one' in
namespace
'urn:nhibernate-mapping-2.2'.
Mapping:
UserMap:
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("tblUsers");
LazyLoad();
Id(user => user.UserID).GeneratedBy.GuidComb();
Map(user => user.UserName).Not.Nullable();
Map(user => user.Password).Not.Nullable();
Map(user => user.IsActive).Nullable();
HasManyToMany(user => user.RolesOfUser).Cascade.All().Inverse().Table("UserInRoles");
}
}
RoleMap:
public class RoleMap : ClassMap<Role>
{
public RoleMap()
{
Table("tblRoles");
Id(role => role.RoleID).GeneratedBy.Identity();
Map(role => role.RoleName).Not.Nullable();
Map(role => role.IsActive).Not.Nullable();
Map(role => role.Description).Not.Nullable();
HasManyToMany(role => role.Users).Cascade.All().Table("UserInRoles");
}
}
Does anyone know what is the issue?
Thanks
HasManyToMany mapping configuration worked for me when I defined Parent and Child Key Column. You can do it like this:
HasManyToMany(user => user.RolesOfUser)
.Table("UserInRoles")
.ParentKeyColumn("UserID")
.ChildKeyColumn("RoleID");

Fluent Nhibernate ClassMaps and Column Order

Our entities have a group of common properties. In order to reduce repetitive mapping, I created a base ClassMap that maps the identities and common properties. For each entity's ClassMap I just subclass the base and it works great. For a new project we are also letting NH generate the DB schema for us. The issue is, the order of the columns is such that the properties from the base ClassMap appear first, followed by anything mapped in the sub class. The requirement for this build is that the columns appear in a specific order.
To get around this I did the following.
public class BaseMap<T> : ClassMap<T> where T : Entity
{
public BaseMap()
{
Id(x => x.Id);
MapEntity();
Map(x => x.CommonProperty1);
Map(x => x.CommonProperty2);
Map(x => x.CommonProperty3);
}
protected virtual void MapEntity()
{
}
}
public class SomeEntityMap : BaseMap<SomeEntity>
{
public SomeEntity()
{
base.MapEntity();
}
protected override void MapEntity()
{
Map(x => x.SomeEntityProperty1);
Map(x => x.SomeEntityProperty2);
Map(x => x.SomeEntityProperty3);
}
}
This works, but feels like a hack. Aside from the hack factor, is there anything here that could be problematic?
If you made the base class and map method abstract it would feel less hacky...
public abstract class BaseMap<T> : ClassMap<T> where T : Entity
{
public BaseMap()
{
Id(x => x.Id);
MapEntity();
Map(x => x.CommonProperty1);
Map(x => x.CommonProperty2);
Map(x => x.CommonProperty3);
}
protected abstract void MapEntity();
}
public class SomeEntityMap : BaseMap<SomeEntity>
{
protected override void MapEntity()
{
Map(x => x.SomeEntityProperty1);
Map(x => x.SomeEntityProperty2);
Map(x => x.SomeEntityProperty3);
}
}
This would keep the common property columns at the end of the table. Be aware that foreign key columns will still get added after those. I don't think there is any way to have full control of the column order w/ fluent, unless you hand-modify the create schema scripts.
I just had to implement something similar myself.
Assuming that you have
public class SomeEntity : Entity
{
...
}
A less 'hack-like' way would be:
public abstract class BaseMap<T> : ClassMap<T> where T : Entity
{
public BaseMap()
{
Id(x => x.Id);
Map(x => x.CommonProperty1);
Map(x => x.CommonProperty2);
Map(x => x.CommonProperty3);
}
}
public class SomeEntityMap : BaseMap<SomeEntity>
{
public SomeEntity()
{
Map(x => x.SomeEntityProperty1);
Map(x => x.SomeEntityProperty2);
Map(x => x.SomeEntityProperty3);
}
}
Same result in the end, but your not using overridden methods to add mappings. It'll be taken care of automagically.

Fluent nhibernate map subclass in rc

I compiled the fluent nhibernate 1.0 rc with nhibernate 2.1 and had several warnings after the errors were fixed.
Fluent nhibernate tells me to use a separate Subclass-map instead of JoinedSubclass.
Current Mapping:
public class ClientMap : ClassMap<Client>
{
public ClientMap()
{
LazyLoad();
Id(x => x.Id);
//some boring stuff in between
JoinedSubClass<Company>("Id", m =>
{
m.LazyLoad();
m.Map(x => x.Name);
m.Map(x => x.Form);
});
}
The classes are inherited (company : client).
I tried the new mapping as follows:
public class CompanyMap : SubclassMap<Company>
{
CompanyMap()
{
LazyLoad();
Map(x => x.Name);
Map(x => x.Form);
}
}
After this change I don't get any companies, I'm not sure about how hibernate correctly knows what to do. Before I sayd "look, I have this class and the subclass I give you straight away in your mapping" and now: "Here are two mappings, figure by yourself, thx" :)
Any advices how to get the new subclass-mapping corrected?
Update:
Now I figured out that this works for saving data but the fk ID is not written to the child. How do I map the FK? The field name is Client_id, as nhibernate expects fk field names..