Possible to use CustomSqlType with CompositeId? - c#

Working with legacy tables, need to create a CompositeId based on two char(3) fields. Don't see any overloads that make this possible with Fluent.
The mapping I'm attempting looks like this:
CompositeId()
.KeyProperty(x => x.LegacyEntity1Id, "LegacyEntity1Id")
.KeyProperty(x => x.LegacyEntity2Id, "LegacyEntity2Id");
Map(x => x.LegacyEntity1Id).CustomSqlType("char(3)");
Map(x => x.LegacyEntity2Id).CustomSqlType("char(3)");
I've also tried:
CompositeId()
.KeyReference(x => x.LegacyEntity1, "LegacyEntity1Id")
.KeyReference(x => x.LegacyEntity2, "LegacyEntity2Id");
Map(x => x.LegacyEntity1Id).CustomSqlType("char(3)");
Map(x => x.LegacyEntity2Id).CustomSqlType("char(3)");
Both result in the same outcome - the table gets generated with a proper composite id, but both columns are the default nvarchar(255). As a result, the foreign keys fail to generate and I get an exception, since the parent tables are char(3).
Is this not possible to map via Fluent?
If not, is there any real difference in mapping it like this*:
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.LegacityEntity1Id).CustomSqlType("char(3)");
Map(x => x.LegacityEntity2Id).CustomSqlType("char(3)");
References(x => x.LegacityEntity1).Column("LegacityEntity1Id").UniqueKey("1").Not.Nullable();
References(x => x.LegacityEntity2).Column("LegacityEntity2Id").UniqueKey("1").Not.Nullable();
* I do have the ability to modify the tables slightly (enough to add an identity), since the legacy tables are being ETLed into a local SQL instance.
Or is there another alternative approach? Can't use a HasManyToMany in this case, for what it's worth (will have a payload).

KeyReference will search the map of the referenced entity and uses the sqltype there. go to the referenced entities and specify Id(x => x.Id).Length(3).

This is how to do it in 2017:
CompositeId()
.KeyProperty(
x => x.LegacyEntity1Id,
k => k.ColumnName("LegacyEntity1Id").Type("AnsiString").Length(3))
.KeyProperty(
x => x.LegacyEntity2Id,
k => k.ColumnName("LegacyEntity2Id").Type("AnsiString").Length(3))

Related

NHibernate Fluent CompositeId with CustomType mapping

I have trouble creating the following mapping:
CompositeId(x => x.Id)
.KeyProperty(x => x.SiteId, "SiteID")
.KeyProperty(x => x.SomeId, "SomeId")
.KeyProperty(x => x.AnotherId, "AnotherId")
.KeyProperty(x => x.Dtg, "DTG");
Previously Dtg is not part of CompositeId so I can just put Dtg as:
Map(x => x.Dtg, "DTG").CustomType("DateTime2");
It requires DateTime2 as millisecond is required.
Now due to a change I will have to make Dtg as part of CompositeId.
So how do I put CustomType to Dtg? thanks for your help.
Solution found, adding .CustomType<TimestampType>() does not truncate milliseconds:
CompositeId(x => x.Id)
.KeyProperty(x => x.SiteId, "SiteID")
.KeyProperty(x => x.SomeId, "SomeId")
.KeyProperty(x => x.AnotherId, "AnotherId")
.KeyProperty(x => x.Dtg, "DTG").CustomType<TimestampType>();

Fluent NHibernate PersistentSpecification Test fails

I currently have these Maps
public class CountryMap : ClassMap<Country>
{
public CountryMap()
{
Table("tblCountry");
Id(x => x.Id, "intCountryId");
Map(x => x.Name, "strCountryName");
HasMany(x => x.FlagImages)
.Table("tblImage")
.KeyColumn("intRelId")
.Where("intObjId=29")
.Not.Cascade.All();
}
}
public class ImageMap : ClassMap<Image>
{
public ImageMap()
{
Table("tblImage");
Id(x => x.Id, "intImgId");
Map(x => x.ObjId, "intObjId");
Map(x => x.RelId, "intRelId");
Map(x => x.ImageName, "strImage");
}
}
and the following persistent specification test:
PersistenceSpecification<Image>(session)()
.CheckProperty(r => r.Id, 1)
.CheckProperty(r => r.ImageName, "ss")
.CheckProperty(r => r.ObjId, (int)ObjectType.Country)
.CheckProperty(r => r.RelId, 102)
.VerifyTheMappings();
Somewhat the test of Image failed.
The failure message is
Assert.AreEqual failed. Expected:<(null)>. Actual:<NHibernate.Exceptions.GenericADOException: could not insert: [HansaCrew.Models.Images.Image][SQL: INSERT INTO tblImage (intObjId, intRelId, strImage) VALUES (?, ?, ?); select last_insert_rowid()] ---> System.Data.SQLite.SQLiteException: constraint failed
foreign key constraint failed
I've checked it for 2 days and haven't find the reason. Any help?
Okay, I got it.
The problem of this piece of code lies here
HasMany(x => x.FlagImages)
.Table("tblImage")
.KeyColumn("intRelId")
.Where("intObjId=29")
.Not.Cascade.All();
NHibernate automatically creates a foreign key constraint with tblImage, which has a lot of intRelIds which is not in the column of intCountryId in the table tblCountry. That's why the test fails saying foreign key constraint failure.
The way to solve this problem is to create a view in the database and then map the view into the Image model

Using a null in where clause of rnHibernate

I am trying to filter out the result in the mapping. However I am trying to filter out the nulls from an int field. nHiberate throw an exception. If I use an number it works. Here is the code:
table("products");
Id(x => x.productID);
Map(x => x.canOverwrite);
Map(x => x.format);
Map(x => x.freeShipping);
Map(x => x.height);
Map(x => x.lastUpdated);
Map(x => x.length);
Map(x => x.releaseDate);
Map(x => x.removeDate);
HasMany(x => x.ProductContributors).Where(c => c.sortID != null).KeyColumn("productID").Not.LazyLoad();
Any suggestions on how to get to this to work?
In the contributors I also had a bool value for disabled. I added that to the entity and mapping. Then I filtered by disabled == false. Not really a solution and more of a work around.

Foreign Key to a table with 2 columns primary key (CompositeId)

I've defined the primary key as following:
CompositeId()
.KeyProperty(x => x.Id)
.KeyProperty(x => x.Type);
I've tried the following:
References(x => x.EntityWith2ColsPK);
And failed with:
Foreign key (Fk_MyEntity_EntityWith2ColsPK:MyEntities [Fk_EntityWith2ColsPK])) must have same number of columns as the referenced primary key (EntityWith2ColsPKs [Id, Type])
How can I reference EntityWith2ColsPK from another entity?
Update:
I've tried the following (according to AlfeG's comment):
HasMany<EntityWith2ColsPK>(x => x.EntityWith2ColsPK).KeyColumns.Add("Id", "Type").Cascade.All();
Which failed with:
Custom type does not implement UserCollectionType: EntityWith2ColsPK
But anyway I don't want a 1 to many relation, I want a 1 to 1 relation. Still, I can't make either of them work.
Also, I've tried:
HasOne<EntityWith2ColsPK>(x => x.EntityWith2ColsPK).PropertyRef(x => x.Id).PropertyRef(x => x.Type);
Which fails with:
NHibernate.MappingException : property not found: Type on entity EntityWith2ColsPK
What can I do for this to really work?
I managed to achieve something in the db.. but yet, for some reason I suspect it maps the property "Type" twice, because I want it to be both part of the Primary Key, and part of the Foreign Key..
This is what I did:
References(x => x.EntityWith2ColsPK).Columns("EntityWith2ColsPKId", "Type").Formula("Id = :EntityWith2ColsPKId AND Type = :Type");
But I received the following exception:
System.IndexOutOfRangeException : Invalid index 8 for this SqlParameterCollection with Count=8.
Because the mapping of this entity is same as EntityWith2ColsPK:
CompositeId()
.KeyProperty(x => x.Id)
.KeyProperty(x => ((ILocalizedEntity) x).Language);
HELP!
You can use something like this since you aren't using cascade anyway on your Reference
References(x => x.EntityWith2ColsPK)
.Columns(new string[] { "ID", "TYPE" })
.Not.Update()
.Not.Insert();

NHibernate fluent update problem (one to many relation)

I have a object OtherFaclilityEntity which contains a IList of OtherFcs objects, and the mapping is as follows:
public OtherFacilityMap()
{
Schema("SOME");
Table("OTHER_FACILITY");
Id(x => x.Id, "OTHER_FACILITY_S").GeneratedBy.TriggerIdentity();
Map(x => x.RowCreator, "ROW_CREATOR");
Map(x => x.RowCreateDate, "ROW_CREATE_DATE");
Map(x => x.Description, "DESCRIPTION");
Map(x => x.ExistenceKdNm, "R_EXISTENCE_KD_NM");
References(x => x.FacilityClassItem, "FACILITY_CLASS_S").LazyLoad(Laziness.False).Fetch.Join().Not.Insert().Not.Update();
HasMany(x => x.FacilityCmList).KeyColumn("WHOLE_S").Fetch.Subselect().Not.LazyLoad();
}
When i try to do a SaveOrUpdate on the OtherFacility entity, it also updates all the entities in the FacilityCmList, which is fine, but in the last sql that is run tries to remove all relations between the parent and the child objects:
NHibernate.SQL: 2011-07-19 10:29:33,111 [361] DEBUG NHibernate.SQL [(null)] - UPDATE SOME.FACILITY_CMS SET WHOLE_S = null WHERE WHOLE_S = :p0;:p0 = '26021842'
I assume it has something to do with my mapping, any ideas?
After reading NHibernate sets Foreign Key in secondary update rather than on initial insert violating Not-Null Constrain on key column i found that i needed to add Inverse to the HasMany relation.
HasMany(x => x.FacilityCmList).KeyColumn("WHOLE_S").Fetch.Subselect().Inverse().Not.LazyLoad();

Categories

Resources