Mapping self-referencing IDictionary<string, Entity> with Fluent NHibernate - nhibernate

I have the following entities in my domain model:
class Entity
{
public int Id { get; set; }
}
class Foo : Entity
{
public IDictionary<string, Attribute> Attributes { get; set; }
}
class Bar : Entity
{
public IDictionary<string, Attribute> Attributes { get; set; }
}
class Attribute : Entity
{
public string Key { get; set; }
public string Value { get; set; }
public IDictionary<string, Attribute> Attributes { get; set; }
}
I'd like to map these dictionaries with Fluent NHibernate. I've gotten most things to work, but first I'm having difficulties with the self-referencing Attribute.Attributes property. This is due to NHibernate making the Key a primary key of the Attribute table as well as the Id it inherits from Entity. This is how my mapping works:
ManyToManyPart<Attribute> manyToMany = mapping
.HasManyToMany<Attribute>(x => x.Attributes)
.ChildKeyColumn("AttributeId")
.ParentKeyColumn(String.Concat(entityName, "Id"))
.AsMap(x => x.Key, a => a.Column("`Key`"))
.Cascade.AllDeleteOrphan();
if (entityType == typeof(Attribute))
{
manyToMany
.Table("AttributeAttribute")
.ParentKeyColumn("ParentAttributeId");
}
If I replace the if statement with the following:
if (entityType == typeof(Attribute))
{
manyToMany
.Table("Attribute")
.ParentKeyColumn("ParentAttributeId");
}
I get the following exception:
NHibernate.FKUnmatchingColumnsException : Foreign key (FK_Attribute_Attribute [ParentAttributeId])) must have same number of columns as the referenced primary key (Attribute [ParentAttributeId, Key])
This is due to NHibernate automatically making Key the primary key alongside Id in my Attribute column. I'd like Key to not be primary key, since it shows up in all of my many to many tables;
create table FooAttribute (
FooId INT not null,
AttributeId INT not null,
[Key] NVARCHAR(255) not null
)
I'd like the foreign keys to only reference Id and not (Id, Key), since having Key as a primary key requires it to be unique, which it won't be across all of my ManyToManys.

where do you map Attribute itself (does it contain a Composite Key)?
AttributeValue may be a better name to show that it contains a value.
.AsMap(x => x.Key) is enough to say that Key should be the dictionary key
create table FooAttribute (
FooId INT not null,
AttributeValueId INT not null
)
or consider using
mapping.HasMany(x => x.Attributes)
.KeyColumn(entity + Id)
.AsMap(x => x.Key)
.Cascade.AllDeleteOrphan();
which will create
create table Attribute (
Id INT not null,
FooId INT,
BarId INT,
ParentAttributeId INT,
Key TEXT,
Value TEXT,
)

Related

NHibernate Exception while building SessionFactory if column name is same for association property

I have Master and Detail tables. Name of Primary Key column in both the tables is same: Id.
While building session factory, I am getting following exception:
NHibernate.MappingException: Unable to build the insert statement for class ........Detail1Entity: a failure occured when adding the Id of the class ---> System.ArgumentException: The column 'Id' has already been added in this SQL builder
Parameter name: columnName
at NHibernate.SqlCommand.SqlInsertBuilder.AddColumnWithValueOrType(String columnName, Object valueOrType)
at NHibernate.SqlCommand.SqlInsertBuilder.AddColumns(String[] columnNames, Boolean[] insertable, IType propertyType)
at NHibernate.Persister.Entity.AbstractEntityPersister.GenerateInsertString(Boolean identityInsert, Boolean[] includeProperty, Int32 j)
--- End of inner exception stack trace ---
at NHibernate.Persister.Entity.AbstractEntityPersister.GenerateInsertString(Boolean identityInsert, Boolean[] includeProperty, Int32 j)
at NHibernate.Persister.Entity.AbstractEntityPersister.GenerateInsertString(Boolean[] includeProperty, Int32 j)
at NHibernate.Persister.Entity.AbstractEntityPersister.PostInstantiate()
at NHibernate.Persister.Entity.SingleTableEntityPersister.PostInstantiate()
at NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
at NHibernate.Cfg.Configuration.BuildSessionFactory()
at ...........
I have following tables:
CREATE Table MasterTable1
(
[Id] [INT] IDENTITY (1,1) NOT NULL CONSTRAINT MasterTable1PK PRIMARY KEY,
[MasterData] [VARCHAR] (100)
)
CREATE Table DetailTable1
(
[Id] [INT] IDENTITY (1,1) NOT NULL CONSTRAINT DetailTable1PK PRIMARY KEY,
[MasterId] [INT] NOT NULL CONSTRAINT DetailTable1_MasterTable1_FK FOREIGN KEY REFERENCES MasterTable(MasterId),
[DetailData] [VARCHAR] (100)
)
Following are entity definitions:
public class Master1Entity
{
public virtual int Id { get; set; }
public virtual string MasterData { get; set; }
}
public class Detail1Entity
{
public virtual int Id { get; set; }
public virtual string DetailData { get; set; }
public virtual Master1Entity Master1 { get; set; }
}
Following are the mappings:
internal class Master1Map : ClassMapping<Master1Entity>
{
public Master1Map()
{
Table("MasterTable1");
Id(x => x.Id, im =>
{
im.Column("Id");
im.Generator(Generators.Identity);
});
Property(x => x.MasterData);
}
}
internal class Detail1Map : ClassMapping<Detail1Entity>
{
public Detail1Map()
{
Table("DetailTable1");
Id(x => x.Id, im =>
{
im.Column("Id");
im.Generator(Generators.Identity);
});
Property(x => x.DetailData);
ManyToOne(x => x.Master1, map => { map.Column("Id"); });
}
}
As explained here, I know that if I rename [MasterTable1].[Id] to [MasterTable1].[MasterId] and modify the entities and mappings accordingly, this will work well.
But, I cannot change the underlying database; this is legacy database I have to take on.
Also, this is Many-to-One relationship. One Master will have multiple Detail entries.
Is there any way to make this work without changing column name in database?
Don't confuse collection mapping (expects column from association table) with entity mapping (expects column from owner table). ManyToOne is entity mapping and it expects column from owner table. In your case owner table for Master1 is DetailTable1 and column you need to map is MasterId:
internal class Detail1Map : ClassMapping<Detail1Entity>
{
...
ManyToOne(x => x.Master1, map => { map.Column("MasterId"); });

Fluent NHibernate automapping composite id with component

I have this complex situation: a database of countries/regions/states/cities which primary key is composed by a code (nvarchar(3)) in a column called "Id" plus all key columns of "ancestors" (regions/states/cities).
So the table country has only one key coumn (Id) while cities has 4 key columns (Id, StateId,regionId,CountryId). Obviously they're all related, so each ancestor column is a foreign key to the related table.
I have Entities in my Model that map this relationships. But they all derive from one type called Entity<T> where T may be a simple type (string, in etc) or a complex one (a component implementing the key).
Entity<T> implements a single property called Id of type T.
For each db table, if it has a comlex key, I implement it in a separate component, which oveerides also Equals and GetHashCode() Methods (in future I'll implement those in the Entity base class).
So I have a RegionKey componet that has 2 properties (Id and CountryId).
I have conventions for Foreign Key and primary key naming and type and that is ok.
I have also Mapping ovverrides for each complex Entity.
For simplicity, lets concentrate only on Countries and Regions table. Here they are:
public class Country: Entity<string>
{
public virtual string Name { get; set; }
public virtual IList<Region> Regions { get; set; }
}
public class Region: Entity<RegionKey>
{
public virtual string Name { get; set; }
public virtual Country Country { get; set; }
}
and the RegionKey component:
namespace Hell.RealHellState.Api.Entities.Keys
{
[Serializable]
public class RegionKey
{
public virtual string Id { get; set; }
public virtual string CountryId { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
return false;
var t = obj as RegionKey;
if (t == null)
return false;
return Id == t.Id && CountryId == t.CountryId;
}
public override int GetHashCode()
{
return (Id + "|" + CountryId).GetHashCode();
}
}
}
Here is the configuration of AutoPersistenceModel:
public ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(
MsSqlCeConfiguration.Standard
.ConnectionString(x=>x.Is(_connectionString))
)
.Mappings(m => m.AutoMappings.Add(AutoMappings))
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
}
private AutoPersistenceModel AutoMappings()
{
return AutoMap.Assembly(typeof (Country).Assembly)
.IgnoreBase(typeof(Entity<>))
.Conventions.AddFromAssemblyOf<DataFacility>()
.UseOverridesFromAssembly(GetType().Assembly)
.Where(type => type.Namespace.EndsWith("Entities"));
}
private static void BuildSchema(Configuration config)
{
//Creates database structure
new SchemaExport(config).Create(false, true);
//new SchemaUpdate(config).Execute(false, true);
}
Here is the Regions entity overrides
public class RegionMappingOverride : IAutoMappingOverride<Region>
{
public void Override(AutoMapping<Region> mapping)
{
mapping.CompositeId(x=>x.Id)
.KeyProperty(x => x.Id, x=> x.ColumnName("Id").Length(3).Type(typeof(string)))
.KeyProperty(x => x.CountryId, x => x.ColumnName("CountryId").Length(3).Type(typeof(string)));
}
}
Ok now when I test this mapping I got an error saying: The data types of the columns in the relationship do not match.
I have also tried this override:
public void Override(AutoMapping<Region> mapping)
{
mapping.CompositeId()
.ComponentCompositeIdentifier(x=>x.Id)
.KeyProperty(x => x.Id.Id, x=> x.ColumnName("Id").Length(3).Type(typeof(string)))
.KeyProperty(x => x.Id.CountryId, x => x.ColumnName("CountryId").Length(3).Type(typeof(string)));
}
And it almost work but it creates a Regions table with a single column key of varbinary(8000) which is not what I want:
CREATE TABLE [hell_Regions] (
[Id] varbinary(8000) NOT NULL
, [Name] nvarchar(50) NULL
, [CountryId] nvarchar(3) NULL
);
GO
ALTER TABLE [hell_Regions] ADD CONSTRAINT [PK__hell_Regions__0000000000000153] PRIMARY KEY ([Id]);
GO
ALTER TABLE [hell_Regions] ADD CONSTRAINT [FK_Regions_Country] FOREIGN KEY ([CountryId]) REFERENCES [hell_Countries]([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
GO
I don't have a clue of how to deal with it since it seems to me everythin is ok.
Thanks in advance for your answers
Ok I menaged to solve it: I had to sign the CompositeId class as MAPPED, since it is a component. So this is my new RegionMappingOverride:
public class RegionMappingOverride : IAutoMappingOverride<Region>
{
public void Override(AutoMapping<Region> mapping)
{
mapping.CompositeId(x=>x.Id)
.Mapped()
.KeyProperty(x =>x.Id,x=>x.Length(3))
.KeyProperty(x => x.CountryId, x=>x.Length(3));
}
}
Now the sql created is correct:
create table hell_Countries (
Id NVARCHAR(3) not null,
Name NVARCHAR(50) null,
primary key (Id)
)
create table hell_Regions (
Id NVARCHAR(3) not null,
CountryId NVARCHAR(3) not null,
Name NVARCHAR(50) null,
primary key (Id, CountryId)
)
alter table hell_Regions
add constraint FK_Region_Country
foreign key (CountryId)
references hell_Countries

Make AskedBy_PersonId the foreign column name(instead of the default AskedBy_id) on Fluent NHibernate

I have these tables:
create table Person
(
PersonId int identity(1,1) primary key,
PersonName nvarchar(100) not null
);
create table Question
(
QuestionId int identity(1,1) primary key,
QuestionText nvarchar(100) not null,
AskedBy_PersonId int not null references Person(PersonId),
QuestionModifiedBy_PersonId int not null references Person(PersonId)
);
And I have these models:
public class Question
{
public virtual int QuestionId { get; set; }
public virtual string QuestionText { get; set; }
public virtual Person AskedBy { get; set; }
public virtual Person QuestionModifiedBy { get; set; }
}
public class Person
{
public virtual int PersonId { get; set; }
public virtual string PersonName { get; set; }
}
I'm using automapping with FluentNHibernate, the referencing properties defaults to these database column names:
AskedBy_id
QuestionModifiedBy_id
How can one make FluentNHibernate make the referencing properties be mapped to this style of foreign column name?
AskedBy_PersonId
QuestionModifiedBy_PersonId
As of now, I'm doing it in manual overriding:
.Override<Question>(x =>
{
x.References(y => y.AskedBy).Column("AskedBy_PersonId");
x.References(y => y.QuestionModifiedBy).Column("QuestionModifiedBy_PersonId");
})
I wanted to remove that overriding and want Fluent NHibernate to automatically make the foreign column name follow the naming pattern above
How can I achieved that with Fluent NHibernate?
Should be easy with IReferenceConvention implementation:
public class ReferenceConvention : IReferenceConvention
{
public void Apply(IManyToOneInstance instance)
{
instance.Column(
instance.Name + "_" + instance.Property.PropertyType.Name + "Id");
}
}
NHibernate should be configured to read the conventions (with something like this):
Fluently.Configure()
//... other configuration
.Mappings(m => m.AutoMappings.Add(
AutoMap.AssemblyOf<Person>()
.Conventions.AddFromAssemblyOf<ReferenceConvention>());

FluentNHibernate Many-To-One References where Foreign Key is not to Primary Key and column names are different

I've been sitting here for an hour trying to figure this out...
I've got 2 tables (abbreviated):
CREATE TABLE TRUST
(
TRUSTID NUMBER NOT NULL,
ACCTNBR VARCHAR(25) NOT NULL
)
CONSTRAINT TRUST_PK PRIMARY KEY (TRUSTID)
CREATE TABLE ACCOUNTHISTORY
(
ID NUMBER NOT NULL,
ACCOUNTNUMBER VARCHAR(25) NOT NULL,
TRANSAMT NUMBER(38,2) NOT NULL
POSTINGDATE DATE NOT NULL
)
CONSTRAINT ACCOUNTHISTORY_PK PRIMARY KEY (ID)
I have 2 classes that essentially mirror these:
public class Trust
{
public virtual int Id {get; set;}
public virtual string AccountNumber { get; set; }
}
public class AccountHistory
{
public virtual int Id { get; set; }
public virtual Trust Trust {get; set;}
public virtual DateTime PostingDate { get; set; }
public virtual decimal IncomeAmount { get; set; }
}
How do I do the many-to-one mapping in FluentNHibernate to get the AccountHistory to have a Trust? Specifically, since it is related on a different column than the Trust primary key of TRUSTID and the column it is referencing is also named differently (ACCTNBR vs. ACCOUNTNUMBER)???? Here's what I have so far - how do I do the References on the AccountHistoryMap to Trust???
public class TrustMap : ClassMap<Trust>
{
public TrustMap()
{
Table("TRUST");
Id(x => x.Id).Column("TRUSTID");
Map(x => x.AccountNumber).Column("ACCTNBR");
}
}
public class AccountHistoryMap : ClassMap<AccountHistory>
{
public AccountHistoryMap()
{
Table("TRUSTACCTGHISTORY");
Id (x=>x.Id).Column("ID");
References<Trust>(x => x.Trust).Column("ACCOUNTNUMBER").ForeignKey("ACCTNBR").Fetch.Join();
Map(x => x.PostingDate).Column("POSTINGDATE");
);
I've tried a few different variations of the above line but can't get anything to work - it pulls back AccountHistory data and a proxy for the Trust; however it says no Trust row with given identifier.
This has to be something simple. Anyone?
Thanks in advance.
You need to use property-ref:
public class AccountHistoryMap : ClassMap<AccountHistory>
{
public AccountHistoryMap()
{
Table("TRUSTACCTGHISTORY");
Id (x=>x.Id).Column("ID");
References(x => x.Trust, "ACCOUNTNUMBER").PropertyRef("ACCTNBR").Fetch.Join();
Map(x => x.PostingDate).Column("POSTINGDATE");
}
}

Specify a Fluent NHibernate automapping to add a unique constraint to all entities

My automapping:
return Fluently.Configure()
.Database(config)
.Mappings(m =>
m.AutoMappings.Add(
AutoMap.AssemblyOf<Company>()
.Where(
t => t.Namespace == "DAL.DomainModel" && t.IsClass)
.IgnoreBase<ReferenceEntity>()))
.BuildSessionFactory();
So ReferenceEntity is an abstract class containing a string Name, and all my reference entities inherit from this class. I'd like to modify my automapping to add a unique constraint to the Name field for all entities that inherit from ReferenceEntity.
I've gathered it has something to do with .Setup but I'm a bit lost on how to proceed.
note: I'm using the Fluent NHibernate v1.0 RTM so conventions will be with the new style if that is relavent to my goal.
If all your entities inherit from ReferenceEntity, wouldn't you want to create the unique constraint for the Name property on all the entities that are mapped?
But if you want to filter by entity base class, you can do it. Use a convention to add the unique constraint to your mappings:
public class NameConvention : IPropertyConvention
{
public void Apply(IPropertyInstance instance)
{
// Check the entity base class type
if (instance.EntityType.BaseType.Name == "ReferenceEntity")
{
// Only add constraint to the .Name property
if (instance.Name == "Name")
{
instance.Unique();
}
}
}
}
To get the convention (and all other conventions in the assembly) picked up by FNH, just add this line the AutoMap setup you have above:
.Conventions.AddFromAssemblyOf<NameConvention>()
Alex,
No the answer doesn't change. Here is an example, using the convention above.
public abstract class ReferenceEntity
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
}
public class User : ReferenceEntity
{
public virtual string Email { get; set; }
}
public class Item : ReferenceEntity
{
public virtual string Description { get; set; }
}
This creates sql of:
create table Users (
Id INTEGER not null,
Email TEXT not null,
Name TEXT not null unique,
primary key (Id)
)
create table Items (
Id INTEGER not null,
Description TEXT,
Name TEXT not null unique,
primary key (Id)
)
As long as these are separate entities, it will create a unique constraint on the .Name property for each entity.