Fluent NHibernate : Conventions / KeyColumn - nhibernate

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

Related

NHibernate inserts twice to base class when saving subclass. Violates unique constraint

I am using fluent nhibernate with a legacy oracle db, and Devart Entity Developer to generate mapping and entity classes.
I have a base table Product, which has several subclasses, including Tour. When saving Tour, nhibernate issues 2 identical inserts to the Product table which violates PK unique constraint.
Product mapping is:
public class ProductMap : ClassMap<Product>
{
public ProductMap()
{
Schema("CT_PRODUCTS");
Table("PRODUCT");
OptimisticLock.None();
LazyLoad();
CompositeId()
.KeyProperty(x => x.Season, set =>
{
set.Type("CT.DomainKernel.Enums.Season,CT.DomainKernel");
set.ColumnName("SEASON");
set.Access.Property();
})
.KeyProperty(x => x.ProductCode, set =>
{
set.ColumnName("PROD_CODE");
set.Length(10);
set.Access.Property();
});
Map(x => x.Name)
.Column("NAME")
.Access.Property()
.Generated.Never()
.CustomSqlType("VARCHAR2")
.Length(200);
HasOne(x => x.Tour)
.Class<Tour>()
.Access.Property()
.Cascade.SaveUpdate()
.LazyLoad();
}
}
Tour mapping is:
public class TourMap : SubclassMap<Tour>
{
public TourMap()
{
Schema("CT_PRODUCTS");
Table("TOUR");
LazyLoad();
KeyColumn("SEASON");
KeyColumn("PROD_CODE");
Map(x => x.Duration)
.Column("DURATION")
.Access.Property()
.Generated.Never()
.CustomSqlType("NUMBER")
.Not.Nullable()
.Precision(3);
HasOne(x => x.Product)
.Class<Product>()
.Access.Property()
.Cascade.SaveUpdate()
.LazyLoad()
.Constrained();
}
}
Tour Entity class:
public partial class Tour2 : Product
{
public virtual Product Product
{
get
{
return this._Product;
}
set
{
this._Product = value;
}
}
}
Any Ideas as to what is going wrong?
The solution to this was to Remove the Property references from Tour to Product, and from Product to Tour, which when thought about, make no sense anyway.

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

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

Fluent NHibernate Uni-Directional one to one mapping

I cant get at One-to-One relationship working with Fluent NHibernate. I have User and UserDetails tables and they 'share' a primary key. How do I map them?
This is my latest/best attempt, this fails with NHibernate.Id.IdentifierGenerationException: attempted to assign id from null one-to-one property: User
User
protected UserMap()
{
Table("user");
Id(x => x.Id)
.Column("user_key")
.GeneratedBy.GuidComb().UnsavedValue(Guid.Empty);
References(x => x.UserDetail)
.PropertyRef(x=>x.User)
.Column("user_key")
.Not.Insert().Not.Update().Cascade.All();
}
UserDetail
protected UserDetailMap()
{
Table("user_detail");
Id(x => x.Id).Column("user_key")
.GeneratedBy.Foreign("User")
.UnsavedValue(Guid.Empty);
References(x => x.User)
.Column("user_key")
.Not.Insert().Not.Update().Unique().Cascade.None();
}
Try this
protected UserDetailMap()
{
Table("user_detail");
Id(x => x.Id)
.Column("user_key")
.GeneratedBy.Foreign("User")
.UnsavedValue(Guid.Empty);
HasOne(x => x.User)
.Constrained();
}

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 table-per-class-hierarchy need to use .Where()?

I have the following mapping for a set of contact classes based off an abstract Contact class implementation.
public class ContactMapping : ClassMap<Contact> {
public ContactMapping() {
Id(x => x.Id).GeneratedBy.GuidComb();
Map(x => x.CreatedDate).Not.Nullable();
Map(x => x.Value).Not.Nullable();
Map(x => x.Level).Not.Nullable();
Map(x => x.Comments);
DiscriminateSubClassesOnColumn("ContactType");
}
}
public class PhoneContactMapping : SubclassMap<PhoneContact> {
public PhoneContactMapping() {
Map(p => p.PhoneType);
DiscriminatorValue("PhoneContact");
}
}
public class EmailContactMapping : SubclassMap<EmailContact> {
public EmailContactMapping() {
DiscriminatorValue("EmailContact");
}
}
public class WebsiteContactMapping : SubclassMap<WebsiteContact> {
public WebsiteContactMapping() {
DiscriminatorValue("WebsiteContact");
}
}
I have an entity class that HasMany EmailContact(s), WebsiteContact(s), and PhoneContact(s).
public class ContactableEntityMapping: ClassMap<ContactableEntity> {
public ContactableEntityMapping() {
Id(x => x.Id).GeneratedBy.GuidComb();
Map(x => x.CreatedDate).Not.Nullable();
Map(x => x.Comment);
HasMany<EmailContact>(x => x.EmailContacts).AsBag().Not.LazyLoad().Where("ContactType='EmailContact'");
HasMany<PhoneContact>(x => x.PhoneContacts).AsBag().Not.LazyLoad().Where("ContactType='PhoneContact'");
HasMany<WebsiteContact>(x => x.WebsiteContacts).Not.LazyLoad().AsBag().Where("ContactType='WebsiteContact'");
HasManyToMany(x => x.Addresses).AsSet();
}
}
If i do not specify there .Where() clauses the class ends up coming back with all rows mapped to EmailContact (since it is first in the listing) if LazyLoading is used, and if lazy-loading is not used I receive an exception as it attempts to cast the classes to the wrong type.
Obviously this is because the SQL executed is not passing in the additional where clause unless I specify it in the mapping. Am I missing something in my mapping, or is the Where mess just something we need to live with?
Thanks for the help!