NHibernate: Composite key, one-to-one relation and "Error performing LoadByUniqueKey" - nhibernate

I have two classes. Class 1:
public class Einsatz
{
public virtual ProjNrPindex Id { get; set; }
public virtual Int32? Knr { get; set; }
public virtual String RessNr { get; set; }
public virtual String AdrNr { get; set; }
public virtual DateTime EndeIst { get; set; }
public virtual DateTime StartIst { get; set; }
public virtual DateTime ArbeitsbeginnIst { get; set; }
public virtual String Kennwort { get; set; }
public virtual Taetigkeit Taetigkeit { get; set; }
public Einsatz()
{
this.Id = new ProjNrPindex();
}
public class ProjNrPindex
{
public virtual Int32? Pindex { get; set; }
public virtual String ProjNr { get; set; }
public override Boolean Equals(Object obj)
{
if (obj as Einsatz == null)
{
return(false);
}
if (Object.ReferenceEquals(this, obj) == true)
{
return(true);
}
ProjNrPindex other = obj as ProjNrPindex;
if (Object.Equals(this.Pindex, other.Pindex) == false)
{
return(false);
}
if (Object.Equals(this.ProjNr, other.ProjNr) == false)
{
return(false);
}
return(true);
}
public override Int32 GetHashCode()
{
Int32 hash = 0;
hash += (this.Pindex != null) ? this.Pindex.GetHashCode() : 0;
hash += 1000 * ((this.ProjNr != null) ? this.ProjNr.GetHashCode() : 0);
return(hash);
}
}
public override bool Equals(object obj)
{
var other = obj as Einsatz;
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return this.Id.Equals(other.Id);
}
public override int GetHashCode()
{
unchecked
{
int hash = GetType().GetHashCode();
hash = (hash * 31) ^ this.Id.GetHashCode();
return hash;
}
}
}
Class 2:
public class Taetigkeit
{
public virtual ProjNrPindex Id { get; set; }
public virtual string Text { get; set; }
public virtual string RessNr { get; set; }
public virtual Einsatz Einsatz { get; set; }
public Taetigkeit()
{
this.Id = new ProjNrPindex();
}
public class ProjNrPindex
{
public virtual Int32? Pindex { get; set; }
public virtual String ProjNr { get; set; }
public override Boolean Equals(Object obj)
{
if (obj as Einsatz == null)
{
return (false);
}
if (Object.ReferenceEquals(this, obj) == true)
{
return (true);
}
ProjNrPindex other = obj as ProjNrPindex;
if (Object.Equals(this.Pindex, other.Pindex) == false)
{
return (false);
}
if (Object.Equals(this.ProjNr, other.ProjNr) == false)
{
return (false);
}
return (true);
}
public override Int32 GetHashCode()
{
Int32 hash = 0;
hash += (this.Pindex != null) ? this.Pindex.GetHashCode() : 0;
hash += 1000 * ((this.ProjNr != null) ? this.ProjNr.GetHashCode() : 0);
return (hash);
}
}
public override bool Equals(object obj)
{
var other = obj as Einsatz;
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return this.Id.Equals(other.Id);
}
public override int GetHashCode()
{
unchecked
{
int hash = GetType().GetHashCode();
hash = (hash * 31) ^ this.Id.GetHashCode();
return hash;
}
}
}
Mappings are:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="RestService"
namespace="RestService">
<class name="Einsatz" table="PLANUNG">
<composite-id name="Id">
<key-property name="ProjNr">
<column name="ProjNr" />
</key-property>
<key-property name="Pindex">
<column name="Pindex" />
</key-property>
</composite-id>
<property name="Knr" column="Knr" />
<property name="AdrNr" column="AdrNr" />
<property name="RessNr" column="RessNr" />
<property name="EndeIst" column="EndeIst" />
<property name="StartIst" column="StartIst" />
<property name="ArbeitsbeginnIst" column="ArbeitsbeginnIst" />
<property name="Kennwort" column="Kennwort" />
<one-to-one name="Taetigkeit" class="Taetigkeit" property-ref="Id"/>
</class>
</hibernate-mapping>
and
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="RestService"
namespace="RestService">
<class name="Taetigkeit" table="PLANBER">
<composite-id name="Id">
<key-property name="ProjNr">
<column name="ProjNr" />
</key-property>
<key-property name="Pindex">
<column name="Pindex" />
</key-property>
</composite-id>
<property name="RessNr" column="RessNr" />
<property name="Text" column="Text" />
<one-to-one name="Einsatz" class="Einsatz" property-ref="Id"/>
</class>
</hibernate-mapping>
The code:
var q = s.CreateQuery("from Einsatz e").List<Einsatz>();
gives me:
Error performing LoadByUniqueKey[SQL: SQL not available]
"The given key was not present in the dictionary."
I am afraid I am doing something horribly wrong but I don't know what. I might add that the database in sql server has no foreign keys so the data is not quite coherent.

your equals method is flawed. it will return false when the other object it gets is not Einsatz which should be ProjNrPindex change it to the much easier implementation:
public override bool Equals(object obj)
{
var other = obj as ProjNrPindex;
return other != null &&
Pindex == other.Pindex &&
ProjNr == other.ProjNr;
}
Also Gethashcode will throw Overflowexception in certain situations use unchecked
public override Int32 GetHashCode()
{
unchecked
{
return Pindex.GetOrDefault().GetHashCode() +
1000 * ((this.ProjNr != null) ? this.ProjNr.GetHashCode() : 0);
}
}

Related

NHibernate multi column ManyToOne mapping with Mapping By-Code

I am trying to convert my FluentNHibernate mappings to NHibernate Mapping By-code using NHibernate 3.3.3. The goal is to upgrade to NHibernate 3.3.3 and to cut down on the number of assemblies being distributed.
However when I compile and run I get the following exception:
NHibernate.MappingException: Multi-columns property can't be mapped through single-column API.
The XML mapping FluentNHibernate gets my looks like this:
<many-to-one cascade="none" class="TextDto" fetch="join" lazy="false" name="Name" not-found="ignore">
<column name="NameTextId" unique="false" />
<column name="LanguageId" unique="false" />
</many-to-one>
Here is my new By-Code mapping:
this.ManyToOne(u => u.Name, c =>
{
c.Cascade(Cascade.None);
c.Class(typeof(TextDto));
c.Columns(
x =>
{
x.Name("NameTextId");
x.Unique(false);
},
x =>
{
x.Name("LanguageId");
x.Unique(false);
});
c.Fetch(FetchKind.Join);
c.Lazy(LazyRelation.NoLazy);
c.NotFound(NotFoundMode.Ignore);
c.Unique(false);
});
This is the old FluentNHibernate mapping:
References(x => x.Name)
.Columns("NameTextId", "LanguageId")
.Cascade.None()
.Fetch.Join()
.NotFound.Ignore()
.Not.Unique()
.Not.LazyLoad();
For Completeness the property type involved:
public class TextDto
{
public TextCompositeId Id { get; set; }
public string PluralText { get; set; }
public string SingularText { get; set; }
public override bool Equals(object obj)
{
var text = (TextDto)obj;
if (text == null) return false;
return this.Id.Equals(text.Id);
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
And an example of the property in an entity:
public class CharacteristicValue
{
public CharacteristicValueCompositeId Id { get; set; }
public TextDto Name { get; set; }
public string LanguageIdentity { get; set; }
public string Value
{
get
{
string value = null;
if (this.ValueMultilingual != null) return this.ValueMultilingual.SingularText;
else if (!string.IsNullOrEmpty(this.ValueMeta)) return this.ValueMeta;
return value;
}
}
public TextDto ValueMultilingual { get; set; }
public string ValueMeta { get; set; }
public override bool Equals(object obj)
{
if (obj == null) return false;
if (object.ReferenceEquals(this, obj)) return true;
CharacteristicValue characteristicValue = obj as CharacteristicValue;
if (characteristicValue == null) return false;
if (this.Id != characteristicValue.Id) return false;
return true;
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
So, how do I get the xml-mapping I used to get with FluentNHibernate but with NHiberbate's Mapping By-Code?
In your mapping, remove the c.Unique(false); from the ManyToOne mapping. This setting we do apply for each column now.
this.ManyToOne(u => u.Name, c =>
{
... // the same as above
// c.Unique(false); // it is setting now related to columns
});
And you will recieve
<many-to-one name="Name" class="TextDto" fetch="join" lazy="false" not-found="ignore">
<column name="NameTextId" unique="true" />
<column name="LanguageId" />
</many-to-one>
If you will change uniqueness on one of the columns:
x =>
{
x.Name("NameTextId");
x.Unique(true); // change here
},
The unique constraint would be added to that column:
<column name="NameTextId" unique="true" />

NHibernate - Could not compile the mapping document

It is my firs time using NHibernate, I'm getting source code for a program from my friend after that, the program is running well after that I'm trying to add "Stock.hbm.xml" as following:
`
<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="NBooks.Core.Models"
assembly="NBooks.Core">
<class name="Stock" table="Stocks" lazy="false">
<id name="ID">
<column name="Stock_ID" />
<generator class="identity" />
</id>
<property name="Stock_name" column="Stock_name" />
<property name="Comp_ID" column="Comp_ID" />
<property name="Stock_Code" column="Stock_Code" />
<property name="Address" column="Address" />
<property name="Nots" column="Nots" />
</class>
</hibernate-mapping>
`
with my class "Stock.cs"
using System;
using System.Collections.Generic;
namespace NBooks.Core.Models
{
public class Stock : BaseModel<Stock>
{
public virtual string Stock_name { get; set; }
public virtual string Stock_Code { get; set; }
public virtual int Comp_ID { get; set; }
public virtual string Notes { get; set; }
public virtual string Address { get; set; }
public virtual bool Inactive { get; set; }
public Stock()
{
}
public Stock(string name)
{
this.Stock_name = name;
}
}
public class StockEventArgs : EventArgs
{
public Stock Stock { get; set; }
public StockEventArgs(Stock Stock)
{
this.Stock = Stock;
}
}
public delegate void StockEventHandler(Stock sender, EventArgs e);
}
the Base model is:
using System;
using System.Collections.Generic;
using NBooks.Core.Util;
using NBooks.Data.NHibernate;
using NHibernate;
namespace NBooks.Core.Models
{
public interface IBaseModel
{
int Id { get; set; }
}
public class BaseModel<T> : IBaseModel
{
IList<string> errors = new List<string>();
public virtual int Id { get; set; }
public virtual bool HasErrors {
get { return errors.Count > 0; }
}
public virtual IList<string> Errors {
get { return errors; }
}
public BaseModel()
{
}
public virtual void Validate()
{
Errors.Clear();
}
public virtual void SaveOrUpdate()
{
ITransaction trans = null;
try {
ISession session = NHibernateHelper.OpenSession();
trans = session.BeginTransaction();
session.SaveOrUpdate(this);
session.Flush();
trans.Commit();
} catch (Exception ex) {
LoggingService.Error(ex.Message);
MessageService.ShowError(ex.Message);
trans.Rollback();
}
}
public virtual void Delete()
{
ITransaction trans = null;
try {
ISession session = NHibernateHelper.OpenSession();
trans = session.BeginTransaction();
session.Delete(this);
session.Flush();
trans.Commit();
} catch (Exception ex) {
LoggingService.Error(ex.Message);
MessageService.ShowError(ex.Message);
trans.Rollback();
}
}
public static T Read(int id)
{
return NHibernateHelper.OpenSession().Load<T>(id);
}
public static IList<T> FindAll()
{
return
NHibernateHelper.OpenSession().CreateCriteria(typeof(T)).List<T>();
}
}
}
when build it appers every thing is well and no errors , when run the error "NHibernate - Could not compile the mapping document Stock.hbm.xml" appears.
Thanx in advance
I noticed you have a typo in you XML:
<property name="Nots" column="Nots" />
I would suggest that you look into using Fluent NHibernate as well. It is strongly typed (for the most part) and the mapping files are easier to read and use lambda expressions so that you don't have to go the XML route.
Your mapping would instead look like this:
public class StockMap(): ClassMap<Stock>
{
public StockMap(){
Id(x => x.Id).Column("Stock_ID").GeneratedBy.Identity();
Map(x => x.Comp_ID);
Map(x => x.Address);
Map(x => x.Notes);
}
}
You have a typo in your mapping
<property name="Nots" column="Nots" />
should be
<property name="Notes" column="Nots" />

NHibernate taking longer time executing simple query

I am facing very strange issue re NHibernate and now it is become headache.
NHibernate is taking longer time (2-3 minute) than expected time (few milliseconds) to execute such a simple query. The database is Oracle and I am using ODP driver. I have checked all necessary configuration re NHibernate and Spring which looks ok to me. When I execute the same query in sqldeveloper, it is giving result in milliseconds.
FYI - When I execute another query which has three inner join with complex model with the same NHibernate configuration, I am getting the result as expected.
In the debug log, I could see below lines where it is wasting time:
2012-08-17 09:53:20,754 [TestRunnerThread] DEBUG - NHibernate.Connection.DriverConnectionProvider - Obtaining IDbConnection from Driver
2012-08-17 09:55:09,369 [TestRunnerThread] DEBUG - NHibernate.AdoNet.AbstractBatcher - ExecuteReader took 108720 ms
NHibernate property settings:
<nhibernatePropertiesSettings>
<setting name="nhibernate.connection.provider" serializeAs="String">
<value>NHibernate.Connection.DriverConnectionProvider</value>
</setting>
<setting name="nhibernate.connection.driver.class" serializeAs="String">
<value>NHibernate.Driver.OracleDataClientDriver</value>
</setting>
<setting name="nhibernate.dialect" serializeAs="String">
<value>NHibernate.Dialect.Oracle10gDialect</value>
</setting>
<setting name="nhibernate.show.sql" serializeAs="String">
<value>true</value>
</setting>
<setting name="nhibernate.query.substitutions" serializeAs="String">
<value>true 1, false 0, yes 'Y', no 'N'</value>
</setting>
<setting name="nhibernate.use.proxy.validator" serializeAs="String">
<value>false</value>
</setting>
<setting name="nhibernate.template.flush.mode" serializeAs="String">
<value>Never</value>
</setting>
</nhibernatePropertiesSettings>
Spring property setting:
<springPropertiesSettings>
<setting name="spring.db.provider" serializeAs="String">
<value>OracleODP-11-2.0</value>
</setting>
</springPropertiesSettings>
Mapping:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="XYZ.PaymentInvestigation.Service.Model.PaymentMessageHistory, PaymentInvestigation.Service.Model" table="MESSAGE_HIST_T" lazy="false">
<composite-id name="PaymentMessageHistoryId" class="XYZ.PaymentInvestigation.Service.Model.PaymentMessageHistoryId, PaymentInvestigation.Service.Model" unsaved-value="undefined">
<key-property name="TransactionDate" column="TRN_DATE" />
<key-property name="TransactionReferenceNumber" column="TRN_NUMBER" />
<key-property name="TransactionTimeStamp" column="TRN_TIMESTAMP" />
<key-property name="HistoryNumber" type="AnsiString" column="HIST_NO" />
<key-property name="SubHistoryNumber" type="AnsiString" column="SUB_HIST_NO" />
</composite-id>
<property name="EntryType" column="ENTRY_TYPE" update="false" insert="false" />
<property name="Location" column="LOC" update="false" insert="false" />
<property name="QueLineId" column="QUE_LINE_ID" update="false" insert="false" />
<property name="DateTime" column="DATE_TIME" update="false" insert="false" />
<property name="SequenceNo" column="SEQUENCE_NO" update="false" insert="false" />
<property name="OperatorInitials" column="OPR_INITIALS" update="false" insert="false" />
<property name="Amount" column="AMOUNT" update="false" insert="false" />
<property name="MsgInfo" column="MSG_INFO" update="false" insert="false" />
<property name="RecordExpired" column="RECORD_EXPIRED" update="false" insert="false" />
<property name="RecordUpdated" column="RECORD_UPDATED" update="false" insert="false" />
<property name="Details" column="DETAILS" update="false" insert="false" />
</class>
Query:
IList<PaymentMessageHistory> paymentMessageHistories =
HibernateTemplate.ExecuteFind(session => session
.QueryOver<PaymentMessageHistory>()
.Where(x =>
x.PaymentMessageHistoryId.TransactionDate == paymentMessageId.TransactionDate &&
x.PaymentMessageHistoryId.TransactionReferenceNumber == paymentMessageId.TransactionReferenceNumber)
.List());
PaymentMessageHistoryId Model:
public class PaymentMessageHistoryId : IEquatable<PaymentMessageHistoryId>
{
public virtual DateTime TransactionDate { get; set; }
public virtual int TransactionReferenceNumber { get; set; }
public virtual double TransactionTimeStamp { get; set; }
public virtual string HistoryNumber { get; set; }
public virtual string SubHistoryNumber { get; set; }
public bool Equals(PaymentMessageHistoryId other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.TransactionDate.Equals(TransactionDate) && other.TransactionReferenceNumber == TransactionReferenceNumber && other.TransactionTimeStamp.Equals(TransactionTimeStamp) && Equals(other.HistoryNumber, HistoryNumber) && Equals(other.SubHistoryNumber, SubHistoryNumber);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (PaymentMessageHistoryId)) return false;
return Equals((PaymentMessageHistoryId) obj);
}
public override int GetHashCode()
{
unchecked
{
int result = TransactionDate.GetHashCode();
result = (result*397) ^ TransactionReferenceNumber;
result = (result*397) ^ TransactionTimeStamp.GetHashCode();
result = (result*397) ^ (HistoryNumber != null ? HistoryNumber.GetHashCode() : 0);
result = (result*397) ^ (SubHistoryNumber != null ? SubHistoryNumber.GetHashCode() : 0);
return result;
}
}
public static bool operator ==(PaymentMessageHistoryId left, PaymentMessageHistoryId right)
{
return Equals(left, right);
}
public static bool operator !=(PaymentMessageHistoryId left, PaymentMessageHistoryId right)
{
return !Equals(left, right);
}
public override string ToString()
{
return string.Format("TransactionDate: {0}, TransactionReferenceNumber: {1}, TransactionTimeStamp: {2}, HistoryNumber: {3}, SubHistoryNumber: {4}", TransactionDate, TransactionReferenceNumber, TransactionTimeStamp, HistoryNumber, SubHistoryNumber);
}
PaymentMessageHistory Model:
public class PaymentMessageHistory : IEquatable<PaymentMessageHistory>
{
public virtual PaymentMessageHistoryId PaymentMessageHistoryId { get; set; }
public virtual string EntryType { get; set; }
public virtual string Location { get; set; }
public virtual string QueLineId { get; set; }
public virtual string DateTime { get; set; }
public virtual string SequenceNo { get; set; }
public virtual string OperatorInitials { get; set; }
public virtual decimal Amount { get; set; }
public virtual string MsgInfo { get; set; }
public virtual double RecordExpired { get; set; }
public virtual string RecordUpdated { get; set; }
public virtual string Details { get; set; }
public bool Equals(PaymentMessageHistory other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.PaymentMessageHistoryId, PaymentMessageHistoryId) && Equals(other.EntryType, EntryType) && Equals(other.Location, Location) && Equals(other.QueLineId, QueLineId) && Equals(other.DateTime, DateTime) && Equals(other.SequenceNo, SequenceNo) && Equals(other.OperatorInitials, OperatorInitials) && other.Amount == Amount && Equals(other.MsgInfo, MsgInfo) && other.RecordExpired.Equals(RecordExpired) && Equals(other.RecordUpdated, RecordUpdated) && Equals(other.Details, Details);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (PaymentMessageHistory)) return false;
return Equals((PaymentMessageHistory) obj);
}
public override int GetHashCode()
{
unchecked
{
int result = (PaymentMessageHistoryId != null ? PaymentMessageHistoryId.GetHashCode() : 0);
result = (result*397) ^ (EntryType != null ? EntryType.GetHashCode() : 0);
result = (result*397) ^ (Location != null ? Location.GetHashCode() : 0);
result = (result*397) ^ (QueLineId != null ? QueLineId.GetHashCode() : 0);
result = (result*397) ^ (DateTime != null ? DateTime.GetHashCode() : 0);
result = (result*397) ^ (SequenceNo != null ? SequenceNo.GetHashCode() : 0);
result = (result*397) ^ (OperatorInitials != null ? OperatorInitials.GetHashCode() : 0);
result = (result*397) ^ Amount.GetHashCode();
result = (result*397) ^ (MsgInfo != null ? MsgInfo.GetHashCode() : 0);
result = (result*397) ^ RecordExpired.GetHashCode();
result = (result*397) ^ (RecordUpdated != null ? RecordUpdated.GetHashCode() : 0);
result = (result*397) ^ (Details != null ? Details.GetHashCode() : 0);
return result;
}
}
public static bool operator ==(PaymentMessageHistory left, PaymentMessageHistory right)
{
return Equals(left, right);
}
public static bool operator !=(PaymentMessageHistory left, PaymentMessageHistory right)
{
return !Equals(left, right);
}
public override string ToString()
{
return string.Format("PaymentMessageHistoryId: {0}, EntryType: {1}, Location: {2}, QueLineId: {3}, DateTime: {4}, SequenceNo: {5}, OperatorInitials: {6}, Amount: {7}, MsgInfo: {8}, RecordExpired: {9}, RecordUpdated: {10}, Details: {11}", PaymentMessageHistoryId, EntryType, Location, QueLineId, DateTime, SequenceNo, OperatorInitials, Amount, MsgInfo, RecordExpired, RecordUpdated, Details);
}
I went through with this NHibernate taking a long time to run query but didn't work for me.
Please help!
Regards,
Milind
public class OracleDataClientDriver2 : OracleDataClientDriver
{
protected override void InitializeParameter(IDbDataParameter dbParam, string name, SqlType sqlType)
{
switch (sqlType.DbType)
{
//Timestamp columns not indexed by Oracle 11g date columns. - Use Date
case DbType.DateTime:
base.InitializeParameter(dbParam, name, SqlTypeFactory.Date);
break;
default:
base.InitializeParameter(dbParam, name, sqlType);
break;
}
}
}
and change the value of connection.driver_class = nameSpace.OracleDataClientDriver2, AssemblyName
One more simple solution than inheriting oracle driver class is to just add type attribute in your property and value will be "Date". this is NHibernate type.
<key-property name="TransactionDate" type="Date" column="TRN_DATE" />

Best way to implement Entity with translatable properties in NHibernate

Consider the following class (simplified in order to focus in the core problem):
public class Question
{
public virtual string QuestionId { get; set; }
public virtual string Text { get; set; }
public virtual string Hint { get; set; }
}
and tables:
Question
- QuestionId ((primary key, identity column and key)
- Code
QuestionTranslation
- QuestionTranslationId (primary key, identity column; not really relevant to the association)
- QuestionId (composite key element 1)
- CultureName (composite key element 2) (sample value: en-US, en-CA, es-ES)
- Text
- Hint
How I can map the Question class so the Text and Hint properties are populated using the current thread's culture. If the thread's culture is changed I would like the Text and Hint properties to automatically return the appropriate value without the need for the Question entity to be reloaded.
Note that I'm only outlining the relevant class and properties from the business side. I'm totally open to any new class or property needed to achieve the desired functionality.
An alternative to Firo's answer (yes, I copied it and adapted it and feel bad about this).
It uses a dictionary and maps the translations as composite element (so it doesn't need the id at all)
public class Question
{
public virtual string QuestionId { get; set; }
public virtual string Text
{
get
{
var translation = Translations[CultureInfo.CurrentCulture.Name];
if (translation != null) return translation.Text
return null;
}
set
{
GetTranslation(CultureInfo.CurrentCulture.Name).Text = value;
}
}
public virtual string Hint
{
get
{
var translation = Translations[CultureInfo.CurrentCulture.Name];
if (translation != null) return translation.Hint
return null;
}
set
{
GetTranslation(CultureInfo.CurrentCulture.Name).Hint = value;
}
}
private QuestionTranslation GetTranslation(CultureInfo.CurrentCulture.Name)
{
QuestionTranslation translation;
if (!Translations.TryGetValue(CultureInfo.CurrentCulture.Name, out translation))
{
translation = new QuestionTranslation()
Translations[CultureInfo.CurrentCulture.Name] = translation;
}
return translation;
}
protected virtual IDictionary<string, QuestionTranslation> Translations { get; private set; }
}
class QuestionTranslation
{
// no id, culture name
public virtual string Text { get; set; }
public virtual string Hint { get; set; }
}
mapping:
<class name="Question">
<id name="QuestionId" column="QuestionId"/>
<map name="Translations" table="QuestionTranslation" lazy="true">
<key column="QuestionId"/>
<index column="CultureName"/>
<composite-element class="QuestionTranslation">
<property name="Text"/>
<property name="Hint"/>
</composite-element>
</bag>
</class>
Edited to reflect changed answer:
public class Question
{
public virtual string QuestionId { get; set; }
public virtual string Text
{
get
{
var currentculture = CultureInfo.CurrentCulture.Name;
return Translations
.Where(trans => trans.CultureName == currentculture)
.Select(trans => trans.Text)
.FirstOrDefault();
}
set
{
var currentculture = CultureInfo.CurrentCulture.Name;
var translation = Translations
.Where(trans => trans.CultureName == currentculture)
.FirstOrDefault();
if (translation == null)
{
translation = new QuestionTranslation();
Translations.Add(translation);
}
translation.Text = value;
}
}
public virtual string Hint
{
get
{
var currentculture = CultureInfo.CurrentCulture.Name;
return Translations
.Where(trans => trans.CultureName == currentculture)
.Select(trans => trans.Hint)
.FirstOrDefault();
}
set
{
var currentculture = CultureInfo.CurrentCulture.Name;
var translation = Translations
.Where(trans => trans.CultureName == currentculture)
.FirstOrDefault();
if (translation == null)
{
translation = new QuestionTranslation();
Translations.Add(translation);
}
translation.Hint = value;
}
}
protected virtual ICollection<QuestionTranslation> Translations { get; set; }
}
class QuestionTranslation
{
public virtual int Id { get; protected set; }
public virtual string CultureName { get; set; }
public virtual string Text { get; set; }
public virtual string Hint { get; set; }
}
<class name="Question" xmlns="urn:nhibernate-mapping-2.2">
<id name="QuestionId" column="QuestionId"/>
<bag name="Translations" table="QuestionTranslation" lazy="true">
<key>
<column name="QuestionId"/>
</key>
<one-to-many class="QuestionTranslation"/>
</bag>
</class>
<class name="QuestionTranslation" table="QuestionTranslation" xmlns="urn:nhibernate-mapping-2.2">
<id name="QuestionTranslationId"/>
<many-to-one name="ParentQuestion" column="QuestionId"/>
</class>
if you have a lot of translations then change ICollection<QuestionTranslation> Translations { get; set; } to IDictionary<string, QuestionTranslation> Translations { get; set; } and map as <map> but normally the above should do it

NHibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

I have an Class with property
[Serializable]
public class MyClass {
public MyClass ()
{
}
public virtual System.DateTime Time {
get;
set;
}
public virtual string Name {
get;
set;
}
public virtual string Department {
get;
set;
}
public virtual string Ip
{
get;
set;
}
public virtual string Address {
get;
set;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
MyClass t = obj as MyClass ;
if (t == null)
return false;
if (this.Time == t.Time && this.Name== t.Name && this.Department== t.Department)
return true;
else
return false;
}
public override int GetHashCode()
{
int hash = 13;
hash = hash +
(null == this.Time ? 0 : this.Time.GetHashCode());
hash = hash +
(null == this.Name? 0 : this.Name.GetHashCode());
hash = hash +
(null == this.Department ? 0 : this.Department.GetHashCode());
return hash;
}
}
I am having my Nhibernate mapping as
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NhibernateTest" assembly="NhibernateTest">
<class name="MyClass" table="NhibernateTest">
<composite-id>
<key-property column="Time" type="DateTime" name="Time"></key-property>
<key-property name="Name" type="string" column="Name" ></key-property>
<key-property name="Department" type="string" column="Department" ></key-property>
</composite-id>
<property column="Ip" type="string" name="Ip" />
<property column="Address" type="string" name="Address" />
</class>
</hibernate-mapping>
I am trying to perform a bulk upload for some 40k data's with using composite key. using the following code.
public void StoreInRDBMS(List<MyClass> FileList)
{
ITransaction transaction = null;
try
{
var stopwatch = new Stopwatch();
stopwatch.Start();
ISession session = OpenSession();
using (transaction = session.BeginTransaction())
{
foreach (var File in FileList)
{
session.SaveOrUpdate(File);
}
session.Flush();
session.Clear();
transaction.Commit();
}
session.Close();
stopwatch.Stop();
var time = stopwatch.Elapsed;
}
catch (Exception ex)
{
transaction.Rollback();
}
}
but the problem is , while iterating in the loop the second record in the list throws this error
{"a different object with the same identifier value was already associated with the session: NhibernateTest.MyClass, of entity: NhibernateTest.MyClass"}
though the records are unique. and also if at all its not it should update the same.
It works file if I flush the session after every iteration in the loop like
foreach (var File in FileList)
{
session.SaveOrUpdate(File);
session.Flush();
session.Clear();
}
which should not be the case and even its talkin 17 mins for 40 k records if done by above method.
Can anybody help regarding the same.
Maybe?
foreach (var File in FileList)
{
session.SaveOrUpdate(File);
session.ExecuteUpdate();
}