Mapping two columns with the same name in nhibernate - nhibernate

I've come across a case, we're I've a column mapped twice (un-beknown to us..), and now updates are throwing the "Parameter +1 doesn't exist error".
Is there any suitable way we can achieve the following mapping?
(Please note, this is an inherited database...)
References(x => x.Matter).Columns(new[] { "c_client", "c_matter" }).NotFound.Ignore();
References(x => x.Client).Column("c_client");

An option for you could be to mark the Client column as read only.
References(x => x.Matter).Columns(new[] { "c_client", "c_matter" }).NotFound.Ignore();
References(x => x.Client).Column("c_client").ReadOnly();
This should make it so NHiberante does not try to update it

This is an invalid mapping. You can't use the same column twice.
My suggestion is that you map c_matter and c_client as scalar properties and use queries to retrieve the corresponding matters and clients.

Related

NHibernate: Problem trying to save an entity containing collections

I need some help.
I'm just starting out with NHibernate and I'm using Fluent for mappings. Everything seemed to work fine until today.
Here is the story:
I have two tables in my db: Store and WorkDay
The first table contains info about the store, and the WorkDay table contains info about the days of week and start/end time when the store is open.
Store contains a Guid StoreID PK column that is referenced in the WorkDay table.
So I have a mapping file for Store where I have a HasMany association with the WorkDay table, and a corresponding POCO for Store.
Now, when I fill in all the necessary data and try to persist it to database, I get an exception telling me that the insert into table WorkDay failed because the StoreID had null value and the table constraint doesn't allow nulls for that column (which is, of course, expected behavior).
I understand the reason for this exception, but I don't know how to solve it.
The reason why the insert fails is because the StoreID gets generated upon insert, but the [b]WorkDay[/b] collection gets saved first, in the time when the StoreID hasn't yet been generated!
So, how do I force NHibernate to generate this ID to pass it to dependent tables? Or is there another solution for this?
Thank you!
Here's the code for StoreMap
public class StoreMap : ClassMap<Store> {
public StoreMap() {
Id(x => x.StoreID)
.GeneratedBy.GuidComb();
Map(x => x.City);
Map(x => x.Description);
Map(x => x.Email);
Map(x => x.Fax);
Map(x => x.ImageData).CustomType("BinaryBlob");
Map(x => x.ImageMimeType);
Map(x => x.Name);
Map(x => x.Phone);
Map(x => x.Street);
Map(x => x.Zip);
HasMany(x => x.WorkDays)
.Inverse().KeyColumn("StoreID").ForeignKeyCascadeOnDelete()
.Cascade.All();
}
}
and this is for the WorkDayMap
public class WorkDayMap : ClassMap<WorkDay>{
public WorkDayMap() {
Id(x => x.WorkDayID)
.GeneratedBy.Identity();
Map(x => x.TimeOpen);
Map(x => x.TimeClose);
References(x => x.Store).Column("StoreID");
References(x => x.Day).Column("DayID");
}
}
NHibernate shouldn't insert the WorkDay first, so there must be an error in your code. Make sure you do all of the following:
Add all WorkDay objects to the WorkDays collection.
Set the Store property on all WorkDay objects to the parent object.
Call session.Save() for the Store but not for the WorkDay objects.
edit: You should also note that ForeignKeyCascadeOnDelete() won't change anything at runtime. This is just an attribute for the hbm2ddl tool. If you want NHibernate to delete removed entries, use Cascade.AllDeleteOrphan().
It probably inserts the Workday before the Store because the first has an identity generator. This forces NH to execute an INSERT statement to generate the ID. guid.comb is generated in memory, NH doesn't need the database.
NH tries to access the db at the latest possible point in time, to avoid unnecessary updates and to make use of batches. Workday is inserted when you call session.Save, Store is inserted when it flushes the session next time (eg. on commit).
You shouldn't use the identity generator (unless you are forced to use it). It is bad for performance anyway.
If it still doesn't work, you probably need to remove the not-null constraint on the foreign key. NH can't resolve it every time. There is some smart algorithm which is also able to cope with recursive references. But there are sometimes cases where it sets a foreign key to null and updates it later even if there would be a solution to avoid it.

NHibernate cascade deletes

I have a one-to-many relationship in data model from A to B. But in my domain API I do not expose "B"s on A (since we will never navigate from from A to B), but have a reference from B to A. Now I want to be able to delete all "B"s when A is deleted. Is it possible? Right now NH is trying first to set FK to null, which I don't want, and cannot since column is not nullable.
A = SupplierType
B = BaseProductCoInsurance
public BaseProductCoInsuranceMap()
{
Table("BaseProductCoInsurance");
Id(x => x.Id, "BaseProductCoInsuranceId");
Map(x => x.CoInsurancePercent).Column("CoInsrPrcnt");
References(x => x.BaseProduct, "BaseProductId");
References(x => x.PolicySupplierType, "PlcySupplierTypeID");
References(x => x.InsuredType, "InsuredTypeCode");
}
If you need to be able to cascade delete then you need to let NHibernate know about the relationship. That said you don't need to make the relationship accessible to others. You could of course have a private collection that only NH knows about.
If you make the relationship lazy loaded you shouldn't even see a performance hit from this.
Another option to consider is to just modify your delete method to also delete the other entity.

Fluent NHibernate - HasMany().WithKeyColumnName

I just got the latest version of Fluent from Google code and it seems some of the mapping has changed since I last used it.
Previously I could Map a relationship using the following when the id I was joining on had a different name in the second table
HasMany(x => x.Roles).WithTableName("tbl_Roles").WithKeyColumn("RoleId");
How is done in the latest release of Fluent?
Thanks
HasMany(x => x.Roles)
.WithTableName("tbl_Roles")
.KeyColumns.Add("RoleId");
Multiple column support was added, so the method signature needed to be improved to make it clear what's happening.
This works for me:
HasMany(x => x.Roles)
.WithTableName("tbl_Roles")
.KeyColumnNames.Add("RoleId");

FluentNHibernate HasMany not filling collection

I have a one to many relationship with the following config
HasMany(x => x.Staff)
.Inverse()
.Cascade.All();
But I get a collection failed to initialize error.
Dont I have to specify the foreignkey here, examples I found do not????
How does it know which is the foreign key?
EDIT: Looking closer at the exception the sql is trying to use field Staff_id
when I have said it is StaffID??
Malcolm
Try
HasMany(x => x.Staff)
.KeyColumnNames.Add("StaffID")
.Inverse()
.Cascade.All();
Staff_id is the auto configure default, although you can set what conventions auto-configure uses.
If you're mapping the collection to an IList<T>, you'll want to add AsBag() or NHibernate will complain about a missing "idx" column. If you want to lazy load the collection add .LazyLoad(). And I usually go with .Cascade.AllDeleteOrphan().

NHibernate Table Update Event

I have this table mapping (details don't really matter I think):
WithTable("COPACKER_FACILITY");
Id(x => x.FacilityNumber, "FACILITY_NUM").GeneratedBy.Sequence("FACSEQ");
Map(x => x.FacilityName, "FACILITY_NAME").Not.Nullable().Trimmed();
Map(x => x.AddressLine1, "ADDR1").Not.Nullable().Trimmed();
...
WithTable("FACIL_OTH_AUDIT_INFO", m =>
{
m.WithKeyColumn("FACILITY_NUM");
m.Map(x => x.ProdnShiftsNum, "PRODN_SHIFTS_NUM").Not.Nullable();
m.Map(x => x.ProdnCapacity, "PRODN_CAPACITY").Not.Nullable();
m.Map(x => x.ProdnLinesNum, "PRODN_LINES_NUM").Not.Nullable();
m.Map(x => x.AuditScore, "AUDIT_SCORE");
m.References(x => x.FacilStatus, "STATUS_IND").Not.Nullable();
});
HasMany(x => x.ComplianceFlags)
.KeyColumnNames.Add("FACILITY_NUM")
.Inverse()
.Cascade.All();
...
The reason for the one to one table is for audit reasons. There's a FACIL_OTH_AUDIT_INFO_HIST table that should get a record for every insert and update in the main table.
My question: How can I know when an insert or update happens in that table so I know to insert an audit record?
Many thanks!
+1 to what kvalcanti said... here's another post that I think explains it a little better though (and shows you how to do it without XML configuration!). I'm doing what this guy is doing on my project and it's working really well.
http://www.codinginstinct.com/2008/04/nhibernate-20-events-and-listeners.html
Caveat: I'm not inserting new objects that need to be saved in this event in my project, which I assume will not be a problem, but I can't say for sure since I'm not doing exactly what you're doing.
I posted the final solution to this problem and thought I'd share
http://robtennyson.us/post/2009/08/23/NHibernate-Interceptors.aspx
You can use event listeners.
try http://nhibernate.info/doc/howto/various/creating-an-audit-log-using-nhibernate-events.html