FAQ Database Discussion Community


NHibernate delete child from parent collection with delete cascade

c#,nhibernate,fluent-nhibernate
I have two simple entities named Country and City. public class Country : Entity { public Country() { Cities = new List<City>(); } public virtual string Name { get; set; } public virtual IList<City> Cities { get; set; } } public class City : Entity { public virtual Country Country...

MemberExpression, build Expression.Property from class

c#,fluent-nhibernate,linq-expressions
Below expression compares property NAME with the value PETER. ParameterExpression pe = Expression.Parameter(typeof(T), "x"); MemberExpression member = Expression.Property(pe, "name"); ConstantExpression value = Expression.Constant("Peter"); exp = Expression.Equal(member, value); What if the property is a class: public class Address { public string Name {get; set;} } Then the expression would look something...

fluent nHibernate Restrictions.Not seems not be working properly

c#,nhibernate,fluent-nhibernate
I have the association: TableA 1 --- * TableB I try to build a query, which returns me the list of the TableA items, whose ALL items (TableB) have a value in the column X and Y. But that query seems to be ignoring that not null condition in the...

Speed up the NHibernate SessionFactory create process

nhibernate,fluent-nhibernate,sessionfactory,uptime
I'm developing a website using Asp .Net MVC and NHibernate as ORM tool. I just implemented some patterns using some principles. These are IoC, Service-Repository and UoW. I'm using almost all features of NHibernate in terms of Caching like below Lazy Loading 2nd Level Cache Query Cache Entity Cache Up...

How do I get a new parent ID when cascade creating from a child in NHibernate?

c#,nhibernate,fluent-nhibernate
I have a parent child relationship where the parent doesn't have a reference to the children - something like this : class Child { int Id { get; set; Parent Parent { get; set; } // + other stuff } class Parent { int Id { get; set; } //...

FluentNhibernate: Query to retrieve distinct values

c#,linq,nhibernate,fluent-nhibernate
Using FluentNhibernate 1.3.0.0, NHibernate 3.3.1.4000 on a DB2 LUW 9.7 database. I want to get some distinct data from only one table / entity. In SQL, it´s easy: select distinct Corporation, CalculationDate, ValuationRule from MySchema.MyTable where State == 0 Now, i´m trying to get those data using Linq, but it...

NHibernate error accessing Informix database - System error occurred in network function

hibernate,nhibernate,fluent-nhibernate,informix,informixdb
I'm having a problem communicating with the Informix database using NHibernate, for a limited time works, but pass that particular time the error happens. Follow the evidence below: 'NHibernate.TransactionException: Begin failed with SQL exception ---> IBM.Data.Informix.IfxException: ERROR [08S01] [Informix .NET provider]Communication link failure. em IBM.Data.Informix.IfxConnection.BeginTransactionObject(IsolationLevel isolevel) em IBM.Data.Informix.IfxConnection.BeginTransaction(IsolationLevel isolevel) em...

SetFetchMode Lazy doesn't overwrite ClassMap settings

c#,nhibernate,fluent-nhibernate,lazy-loading
In Criteria I do SetFetchMode as Lazy but still fetching all items, how can I fix this? public class MenuItem : BaseClass<MenuItem> { public virtual int MenuItemId { get; set; } public virtual string Text { get; set; } public virtual IList<MenuItem> Children { get; set; } public virtual MenuItem...

Outer right join doesn't work in NHibernate

mysql,nhibernate,orm,fluent-nhibernate,hql
So I'm having two tables: Table 1: Item id : int title : varchar comments : varchar Table 2: Rating id : int isUpvote : bit date : datetime item_id : int One Item can have several ratings. IsUpvote states whether a Rating is a like or dislike. I'm using...

extention method with type specific List

c#,fluent-nhibernate,extension-methods
I want to create an extention method to bind a List, but getting this error. menuItem.Children.Bind(); public static class Extensions { public static void Bind(this IList list) { //some stuff } } class MenuItemMap : Mapper<MenuItem> { public MenuItemMap() { Id(x => x.MenuItemId); Map(x => x.Text); HasMany(x => x.Children).KeyColumn("ParentId");...

Oracle managed driver ODP.NET with NHibernate 4.0 FLOAT (126) to C# DECIMAL/Double

nhibernate,oracle11g,fluent-nhibernate,decimal,buffer-overflow
I am trying to create a mapping using Fluent NHibernate with Oracle 11g. This is the mapping I am creating:- public class Abc : ClassMap<Abc> { public Abc() { Table("Abc"); DynamicUpdate(); Id(x => x.Id, "IdColumn").GeneratedBy.GuidComb(); Map(x => x.DecimalColumn, "DecimalColumn").Formula("TRUNC(DecimalColumn, 28)"); } } Now when I get the data using criteria...

Search in Fluent-NHibernate using session.QueryOver<> return empty

c#,fluent-nhibernate,fluent-nhibernate-mapping
Hey everyone I am new to ORM, Im using Fluent NHibernate in my CRUD seems to have a problem in my search, it will return an empty or null value and also I can insert data, but when i insert another record its seems updating bcoz it replace my previous...

Bi-directional relationship in nhibernate 4.0

c#,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
I have a code that was working perfectly on NHibernate 3.1, but when it is not working on NHibernate 4.0 So, this is the class relations public class Employee : BaseEntity { ... public Department Dept { get; set; } } public class Department : BaseEntity { ... public IList<Employee>...

"An invalid or incomplete configuration was used while creating a SessionFactory” NHibernate

c#,asp.net-mvc,fluent-nhibernate
I am getting this error while creating SessionFactory. Here is the code, if some can check this out. class NHibernateHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) { InitializeSessionFactory(); } return _sessionFactory; } } private static void InitializeSessionFactory() { _sessionFactory =...

Fluent Nhibernate mappings / Join

c#,nhibernate,fluent-nhibernate
In my code I have an three main entities: 1. Company 2. Staff 3. Position A staff can have several positions in various companies. I want to retrieve all staff associated to a specific company. In code I would do something like: public partial class Company { public virtual IEnumerable<Position>...

Fluent NHibernate Join mapping to Joined table

c#,oracle,nhibernate,fluent-nhibernate
I have entity like: class Doc { public virtual int Id {get;set;} public virtual int Code {get;set;} } where Id is identity. And Code is placed in another table. to get Code I use next SQL statement: Select Distinct A.CODE from DOCLIST D Left Join DOCSLINKS DL On DL.TODOC_ID=D.DOC_ID Left...

Fluent nHibernate PropertyRef is eagerly fetching referenced records. Can I disable it?

c#,nhibernate,fluent-nhibernate
If I specify PropertyRef on References (Many to One) - it eagerly fetches all related records: References(x => x.Panel).PropertyRef(x => x.Code).Not.Insert().Not.Update(); Can I disable that N + 1 select problem? Here I can see that this problem is known, but is there any workaround? Lazy loading not working for many-to-one...

NHibernate mapping returns null value

nhibernate,fluent-nhibernate,nhibernate-mapping
I have a problem with mapping in NHibernate. The Order table has the Invoice_Id column which is the nullable FK to the Invoice table. The problem is, when I load an Invoice which Id exists in the Order table, I see that ConnectedOrder property is null, why? public class Invoice...

Fluent Nhibernate - configure all dates to be rehydrated from UTC

datetime,nhibernate,configuration,fluent-nhibernate,utc
This SO question talks about "Rehydrating fluent nhibernate configured DateTime as Kind Utc rather than Unspecified". One of the later answers in that question has this: Map(x => x.EntryDate).CustomType<UtcDateTimeType>(); That works for one property on one entity. I would like to know if there is a way to specify that...

FluentNHibernate HiLo - can be maxLo read from table and not to be hardwired in code?

c#,.net,nhibernate,fluent-nhibernate,nhibernate-configuration
I am using GeneratedBy.HiLo(string table, string column, string maxLo, string where); for primary key. Currently I am looking for possibility how to load maxLo from table rather than store it as a constant in code. Value for NextHi is loaded from database table (ok, it must be otherwise whole concept...

Having different automapping “configurations”

c#,nhibernate,fluent-nhibernate,fluent-nhibernate-mapping,automapping
I want to have two different mapping configurations. I need to somehow pass arguments to conventions so they can behave differently. Beside using lock and static fields how can I do this?

NHibernate : No update with composite key

c#,nhibernate,fluent-nhibernate
I have an object that is saved using Nhibernate. This object use a composite key and is declared like this : CompositeId() .KeyProperty(x => x.CreditorName) .KeyProperty(x => x.CreditorIBAN) .KeyReference(x => x.Config, "ProfileName"); Map(x => x.ID, "ID").ReadOnly(); Map(x => x.CreationDate, "CreationDate").Default(null); Map(x => x.ContractReference, "ContractReference"); Map(x => x.CreditorBIC, "CreditorBIC"); References<C_ContractType>(x =>...

NHibernate HQL Inner Join (SQL Server,Visual C#)

c#,sql-server,nhibernate,fluent-nhibernate,hql
I want to using HQL with inner Join. But, a query syntax exception is thrown. This is my C# code: string sqlQuery = "Select fq FROM Answers as fq INNER JOIN Questions as q " + " on fq.questionId=q.questionId"; IList Result; int count = 0; try { using (ISession session...

Automapper and NHibernate: lazy loading

c#,nhibernate,fluent-nhibernate,automapper
I have the following scenario. public class DictionaryEntity { public virtual string DictionaryName { get; set; } public virtual IList<DictionaryRecordEntity> DictionaryRecord { get; set; } } public class DictionaryDto { public string DictionaryName { get; set; } public IList<DictionaryRecordEntity> DictionaryRecord { get; set; } } I'm using Automapper and NHibernate....

Fluent nHibernate - how to select DISTINCT dates without time?

c#,fluent-nhibernate
let's say I have a column (datetime) with the following values: 2015-05-16 20:17:05.033 2015-05-16 20:29:07.130 2015-05-17 01:01:04.690 2015-05-17 01:02:28.053 2015-05-17 11:24:37.667 2015-05-17 11:25:24.913 How can I select the distinct list to the DateTime list to 2015-05-16 2015-05-17 ? In plain SQL, I can just do DISTINCT CONVERT(date, myDateColumn) but how...

Database field with multiple allowed value types

c#,postgresql,nhibernate,fluent-nhibernate,domain-driven-design
I am using Fluent NHibernate in my ASP.NET MVC Application to retrieve and save data to a Postgresql database. Say you have a table which holds Fields {Name, DataType, Value} //Model public class Table { public virtual string Name { get; set;} public virtual string DataType { get; set;} public...

Expression.Call, Int32 and Enum

c#,fluent-nhibernate,expression,kendo-grid
Can't figure out how to build an expression that compares an enum type with an int. I have a MVC site with Kendo components embedded. In the view-class, the property is an ENUM, but the view returns an Int32 (the source is a Kendo IFilterDescriptor). So the problem is...: I...

Mapping a Component inside a Component Collection

nhibernate,fluent-nhibernate,domain-driven-design
I'm trying to map a value object collection where these contain other value objects but am getting the below exception. nHibernate Exception: ----> NHibernate.PropertyNotFoundException : Could not find a getter for property '_timeAtAddress' in class 'CustomerAddress' Domain: public class CustomerAddress { private TimePeriod _timeAtAddress; protected CustomerAddress() { } public CustomerAddress(TimePeriod...

How can I do case insensitive and concatenated field searches using nhibernate / linq?

c#,linq,nhibernate,fluent-nhibernate
I have an asp.net-mvc website that uses Fluent Nhibernate Linq / SQL Server. I have a textbox where someone can enter a name and that generate the following query that I am using now to search my Person table: return Session.Query<Person>() .Where(r => (r.LastName.Contains(s) || r.FirstName.Contains(s))); This works as expected...

NHibernate - SafeHandle Cannot be Null

c#,nhibernate,oracle11g,fluent-nhibernate
I am using NHibernate to connect to an Oracle database. Everything was fine until I suddenly started to get the strange Value cannot be null. Parameter name: SafeHandle cannot be null. error. I am not sure what I have changed to get this error and I do not know what...

Could not resolve property on KeyColumn

c#,nhibernate,fluent-nhibernate
I am getting this error on return of ByParameter because of KeyColumn I guess, how can I make this work? could not resolve property: ParentId of: Entity.MenuItem Entity.MenuItem.READ.ByParameter("ParentId", 3); Code: public static IList<T> ByParameter(String Parameter, Object Value) { using (var session = NHibernateHelper<T>.OpenSession()) { var conjunction = new Conjunction(); conjunction.Add(Restrictions.Eq(Parameter,...

QueryOver ProjectionList with different root entity types

c#,nhibernate,fluent-nhibernate,queryover,nhibernate-queryover
I'm having issues trying to reuse ProjectionLists in NHibernate QueryOvers. I can't work out how to reuse things for different root entities. Object model is roughly represented as: Breakfast one to many Pastry many to zero-or-one Coffee The two separate queries are roughly: session.QueryOver<Breakfast>() .Where(b => b.Id == searchId) .Inner.JoinQueryOver(b...

NHibernate fluent mapping to an entity property

asp.net-mvc-4,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
I have a table called "Customers" and in this table there are store and office address. In the code there is a Customer class with two properties that are of type Address (one for StoreAddress and OfficeAddress). public class Customer { public virtual int Id { get; set;} public virtual...

Fluent NHibernate creating entities - why virtual

c#,fluent-nhibernate
I'd like to ask some questions about Fluent NHibernate as I'm developing in it almost a year but still there are some things which I don't get. First questions is about entities as the title says. Why do I make them virtual? A senior developer told me, that when I...

Where clause not working with parantheses

nhibernate,fluent-nhibernate,expression-trees,nhibernate-queryover
Suppose the following Query using a NH 3.4 and RepositoryPattern var list = _repository .QueryOver() .Where(x => (x.Age > 20)) // notice the parantheses .Future() .ToList(); Whith these parantheses added the NH is failing to work, and causes a SO exception. If replacing .Where(x => (x.Age > 20)) with .Where(x...

fluent NHibernate session exception handling

c#,nhibernate,fluent-nhibernate
How should NHibernate exceptions be handled during sessions ? There are many examples over the internet: http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-exceptions https://svn.code.sf.net/p/nhibernate/code/trunk/nhibernate/src/NHibernate/ISession.cs And many, many StackOwerflow threads that suggest an approach similar to this: using (ISession session = factory.OpenSession()) using (ITransaction tx = session.BeginTransaction()) { try { // do some work ... tx.Commit(); }...

Getting 'Index was out of range. Must be non-negative and less than the size of the collection.' when saving a NHibernate entity

c#,nhibernate,fluent-nhibernate
My problem is when saving a NHibernate entity here is the (pseudo)code: using (var session = OpenSession()) { using (var trans = session.BeginTransaction()) { var reportTemplateVersion = new ReportTemplateVersion { ReportTemplateVersionOid = "0B89DB6-6CC1-460A-B913-10AFCF0C868 ", Description = "Testing", TextID_Description = "144bbdda-3249-4c51-8371-3c7ee551b75b ", ChangeTimeStamp = DateTime.Now, HasBeenUsed = false, PartFactory = "010",...

Fluent NHibernate - exception occurred during configuration

fluent-nhibernate
I am using Fluent NHibernate with an external 'hibernate.cfg.xml' file. by machine name like this "Environment.MachineName + ".cfg.xml"" Following is the configuration code where I am getting error: public static bool BuildSessionFactory() { if (_sessionFactory != null) return false; var configuration = new NHibernate.Cfg.Configuration(); configuration.Configure(Environment.MachineName + ".cfg.xml"); configuration.AddAssembly(System.Reflection.Assembly.GetExecutingAssembly()); _sessionFactory =...

How to use “static data” properly with (Fluent) NHibernate

c#,design-patterns,nhibernate,fluent-nhibernate
In our database we have "static data" where ids are assigned manually by hand and they are the same through out the whole life of project. In various places, we check if objects have the same ids with these static data such as: public static void UpdateSlotCapacity(MagazineSlot slot) { using...

Fluent NHibernate mapping via middle table

c#,nhibernate,fluent-nhibernate
I have a scenario that requires a mapping that needs to be done with joins to 2 tables via a middle table (see example) currently it is achieved via a formula which translates to a subquery, but i would like to use joins to do this more efficiently. please help...

How to map a string collection from another table in Fluent NHibernate?

fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
I have an entity: public class Foo { public virtual int Id; public virtual IEnumberable<string> Bars; } And its mapping: public class FooMapping : ClassMap<Foo> { public FooMapping() { Table("foo_table_in_database"); Id(x => x.Id, "Id"); HasMany(x => x.Bars) .AsList() .Table("bars_table_in_db") .Element("BarId", m => { m.Type<string>(); }); } } And an exception...

Fluent NHibernate automap PostGIS geometry type

c#,nhibernate,fluent-nhibernate,postgis
Given the following model: using NetTopologySuite.Geometries; public class bounding_box { public virtual int id { get; protected set; } public virtual Polygon area { get; set; } } How do I automap the area property to a area geometry(Polygon) column when generating the DB schema using Fluent Nhibernate? Note that...

NHibernate. QueryOver Take(n) - with Left.Join

nhibernate,fluent-nhibernate,queryover,nhibernate-queryover
Got some strange behaviour when using Take() with join. Suppose the following example: Comment comment = null; var persons = _repository .QueryOver() .Left.JoinAlias(x => x.Comments, () => comment) .Where(x => x.Age > 20) .Take(5) .Future() .ToList(); Well I'd expect that 5 persons are present in the array, and each of...

What is the proper way to map a Multi-column usertype inside a fluent NHibernate SubclassMap?

c#,nhibernate,fluent-nhibernate,usertype
For a project I'm working on I'm using a custom type to deal with IP Addresses in the database as a binary and address family pair. If I attempt to map to my custom type in a SubclassMap it fails with a Mapping exception during startup NHibernate.MappingException: property mapping has...

NHibernate - NonUniqueObjectException

nhibernate,fluent-nhibernate
The TL;DR version is this: I keep getting a NonUniqueObjectException when trying to delete an entity in a unit test. Can anyone tell me how NHibernate checks the cache and compares objects if it is not using the Equals methods or GetHashCode? I have an application I am trying to...

Mapping to Date part of Sql DateTime

c#,sql-server,nhibernate,fluent-nhibernate,nhibernate-mapping
I have a requirement to be able to fetch data related to a particular Date as opposed to DateTime, for a particular colmumn. Is it at all possible to Map the related objects according to an extracted date part of a date time? Where no explicit foreign key relationship exists...

How can i set a Column in a CompositeId mapping with NHibernate

c#,visual-studio-2013,fluent-nhibernate,mapping,firebird
I have one Composite Id map with NHibernate and I want to set a column in all those Id's. Is that possibel? public class MapProduction : ClassMap<Production> { public MapProduction() { CompositeId() .KeyProperty(c => c.ProductionCode) .KeyProperty(c => c.Cycle) .KeyProperty(c => c.Crop) .KeyProperty(c => c.TechnologyLevel); Map(c => c.Area).Column("A_ARE"); Map(c => c.Productivity).Column("P_ARE");...

NHibernate QueryOver with IUserType fails

c#,nhibernate,fluent-nhibernate,queryover,iusertype
I have a custom user type with NHibernate and the custom type works fine for saving and updating. However an error occurs when using QueryOver on this custom user type. I get the error message: could not resolve property: SpecialType.Code of: NHibernateComplexIUserTypeExample.Person. I know that I can map the SpecialType...

NHibernate Purge/Truncate Table and repopulate in single transaction

.net,nhibernate,fluent-nhibernate
Have a table with no relationships and an integer primary key. Using NHibernate I want to repopulate the table in a single transaction like so: openTrans delete all rows insert new rows (many will have same ID as those deleted previously) commitTrans However NHibernate throws 'a different object with the...

How do I setup Id of entity with a ConventionBuilder in Fluent NHibernate

c#,fluent-nhibernate,fluent-nhibernate-mapping
I have following fluent configuration var sessionFactory = Fluently.Configure() .Database(configuration) .Mappings(arg => { var autoMap = AutoMap.Source(typeSource); foreach (var convention in typeSource.GetConventions()) { autoMap.Conventions.Add(convention); } autoMap.BuildMappings(); }) .BuildSessionFactory(); I use an instance (typeSource) of FluentNHibernate.ITypeSource that also has a method GetConventions, which returns System.Collections.Generic.IEnumerable<FluentNHibernate.Conventions.IConvention>. The result of...

adding initial rows into tables using Fluent migrator

asp.net-mvc-5,fluent-nhibernate,fluent-nhibernate-mapping,fluent-migrator
Im a classic programmer that is newbie at generics and this is an asp.net MVC5 sample application for learning purposes of integrating authorization (users/roles) using fluent migrator lib. I wantto add some sample datas into tables as they created (using migrator console tool). getting compilation error: USERNAME does not exist...

Moving an NHibernate-heavy application from single-tenancy to multi-tenancy with multiple schemas

c#,nhibernate,fluent-nhibernate,multi-tenant,fluent-nhibernate-mapping
I currently have a single-tenant application that uses fluent-nhibernate mappings to map C# objects to tables in my MySQL database. As part of an effort to bring multi-tenancy to my application, I am considering having a single schema for each tenant. That is, I will have n schemas with identical...

Querying via NHibernate without an N+1 - sample included

c#,nhibernate,fluent-nhibernate
I have an N+1 problem and I'm not sure how to solve it. A fully-reproducible sample may be found at the bottom of this question. So if you are willing, please create the database, set up the NUnit test and all the accompanying classes, and try to eliminate the N+1...

NHibernate QueryOver with Nested Classes

c#,nhibernate,fluent-nhibernate
I am using NHibernate's QueryOver to populate an IEnumerable of a class that has many nested classes. However, this is yielding a lot separate select statements in Sql Profiler. Using the example below, NHibernate selects results from the foo table, then "loops" through each row in the result set, selecting...

setting self as createby

nhibernate,fluent-nhibernate
A user can either register themselves or can be created by another user. When a user is created, the CreateBy is set to the user who created the new user. When the user registers, we want to set the CreateBy to the user who is registering. public class User {...