FAQ Database Discussion Community


NHibernate QueryOver CASE WHEN calculate on column value

select,nhibernate,case,queryover
I have been trying to do the following T-SQL in NHibernate QueryOver, but have not succeeded: SELECT Id, SUM(CASE MyValue WHEN 1 THEN Volume ELSE Volume * -1 END) FROM MyTable GROUP BY Id I am trying to sum up all Volume, but for MyValue=1 should be positive values otherwise...

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...

Select from Table Valued Function nhibernate

c#,sql-server,nhibernate,hql,user-defined-functions
I need a little help on this. I'm trying to use a table-valued function in a select, but I got the error that this is not mapped. dbo.FnListEvnt is not mapped [from dbo.FnListEvnt(:dt, :id, :code) ] Function CREATE FUNCTION [dbo].[FnListEvnt] (@DT DATETIME, @ID INT, @CODE VARCHAR (4)) RETURNS @RESULTADO TABLE...

NHibernate - using CreateMultiQuery

c#,nhibernate
My object model contains a Server entity which has collections of Adapter and Configuration objects. I am trying to figure out how I can efficiently retrieve the details of a Server using a Multi Query as outlined in this article. So far, based on the linked article, I have the...

Why NHibernate's interface IQueryOver's method “Where” available in one context, but in other's not?

c#,nhibernate,queryover,nhibernate-queryover
Here is the first situation using (ISession session = NHibernateHelper.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.QueryOver<T>().Where() // all ok } } Here is the same interface but in other class productRepository.ExecuteQuery(over => { IQueryOver<Product> inOtherContext = over; inOtherContext.Where // where method not exists }); I'm sure there's no...

NHibernate: Read uncommited columns

c#,sql,nhibernate
Is it possible to read (i.e. select) columns in the same transaction where they are written to the db in? My code looks like this: using (IGenericTransaction trans = m_GenericSession.BeginTransaction()) { //persist a column to table tExample with Id = 1 WriteSubItems(); trans.Commit(); } public void WriteSubItems() { IDbTransaction trans...

IQueryable Where only class name is known

c#,linq,nhibernate,linq-query-syntax
What I have: session.Query<Symptom>().First(); What I am trying to do: var className="Symptom" session.Query<className>().First() Is it possible to do this in some way? If yes where to look because I've tried with Type.GetType etc, without success. And secondary question, I have to send via web request "type" that will be in...

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...

NHibernate Criteria Where any element of list property is true

c#,nhibernate,hql,criteria,restrictions
I have an already created NHibernate Criteria query that I need to modified so I can add a new condition. The query is based on the Order object, which has a list of OrderItems and then, every OrderItem has a bool property named FinalDeliveryIndicator. In my Criteria query I need...

Nhibernate and like statement on XML field

nhibernate
I have a wrapped fluent nhibernate framework that I'm reusing and have no control over the actual mapping. In my entity object I have a property mapped as string to an XML column in sql. Hence when I run a query like: var myResult = (from myTable in DataManager.Session.Query<Table>() where...

NHibernate query performance with a large number of disjunctions and conjunctions

c#,sql,hibernate,nhibernate
I'm trying to apply a filter to data from an NHibernate session using disjunctions and conjunctions. I have implemented this as follows: var disjunction = new Disjunction(); foreach (var entry in filterCriteria.SelectedCriteria) { var conjunction = Restrictions.Conjunction(); conjunction.Add(Restrictions.Eq("SourceAccount", entry.SourceAccount)); conjunction.Add(Restrictions.Eq("SourceItemId", entry.SourceItemId)); conjunction.Add(Restrictions.Eq("SourceProgram", entry.SourceProgram)); disjunction.Add(conjunction); }...

Nhibernate QueryOver Project enum description to string

c#,nhibernate
Let`s say we have the following query using Nhibernate: var query = session.QueryOver<TenantOrder>(() => tenantOrderAlias) .JoinAlias(() => tenantOrderAlias.Tenant, () => tenantAlias) .JoinAlias(() => tenantAlias.Building, () => buildingAlias) .WhereRestrictionOn(x => tenantOrderAlias.Id.OrderId).IsLike(order.Id); query.Select( Projections.Property(() => tenantAlias.Id).WithAlias(() => tenantDto.Id), Projections.Property(() => tenantAlias.TenantNr).WithAlias(() => tenantDto.TenantNr),...

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...

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",...

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...

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,...

Create relation one-to-many without Foreign Key in nhibernate4

c#,nhibernate,db2,nhibernate-mapping,nhibernate-4
i'm new to NHibernate 4 and i try to create a one-to-many relation between two table in DB2, the tables don't have a foreign key and i can't edit the tables. When debug the application i catch error in .saveorupdate method. The tables contains: TLDMAIN->summary of article TLDDETAIL->detail of article...

NHibernate SchemaExport.Execute does not create table

c#,nhibernate,nunit,nhibernate-configuration
Learning NHibernate by following this tutorial Your first NHibernate based application and I got to the point where you call new SchemaExport(cfg).Execute(true, true, false); in a test method to export the schema (create the Product table) for verifying NHibernate was set up correctly [Test] public void Can_generate_schema() { var cfg...

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 =>...

How to specify Schema for Lists while mapping Nhibernate by code

nhibernate,nhibernate-mapping
I want my "tag_post" table to be created in "article" schema but it's created in "public" schema. List(x => x.Tags, l => { l.Where("deleted = 0"); l.Key(k => { k.Column("post_id"); k.NotNullable(true); }); Schema(Constants.DatabaseSchemaNames.Article); l.Table("tag_post"); }, x => { x.ManyToMany(m => m.Column("tag_id")); }); ...

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>...

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...

Trouble combining Linq Expressions into a Func

linq,nhibernate,ienumerable,iqueryable
I've been trying to factor some common lambda subexpressions out into reusable components and have hit a wall. I'll show what I've done so far with a simplified example and hope one of you can shed some light. My subexpressions are ultimately used in an NHibernate Query (IQueryable interface). Here's...

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...

NHibernate: ProjectionList: Can we create dynamic projectionlist for Orderby

nhibernate,queryover,nhibernate-queryover,nhibernate-projections
I am working on a query in NHibernate in which user could provide a sorting order for some selected fields. I need to do a OrderBy() in QueryOver with the names of field names in entities, but when using projection list I am getting like this. SELECT this_.Number as y0_,...

Migrating from Nhibernate to EF6

c#,sql-server,database,entity-framework,nhibernate
I currently have an .NET application that has a SQL Sever database with GUIDs for Primary Keys. We are using NHinbernate for the ORM but want to switch to the latest version of Entity Framework and use Identities(INTs) as our Primary Keys. Does anyone have any experience or references that...

NHibernate: Better to store reference to another Entity or the entity's ID?

c#,c#-4.0,nhibernate
New to NHibernate and C#. I have these two classes: User //Simplified version { private long _id; private String _username; // unique private ISet<Role> _roles; //Properties } and Role { private long _id; private String _name; //Properties } Is it better to store a reference to the Role class (as...

How to update object with lazy properties (proxy object) in another session?

c#,nhibernate,proxy-object
I attempted to get the object that has lazy properties in a session and tried to update it in another session. But it failed to do so with an Error: No persister for SecUserProxy (actual class is SecUser) I'm using NHibernate 3.4. When I googled I came to know its...

NHibernate - Add new property to class

nhibernate
I'm a little confused about what goes on behind the scenes in NHibernate when I add a new property to a class. When I add a property 'Price' to an 'Item' class, my application throws an exception when retrieving Item objects because this new property isn't in the database: [SqlException...

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...

Why NHibernate requires the entities methods to be virtual?

nhibernate
NHibernate requires your entities properties and methods to be marked as virtual to do all its magic. While I don't know NHibernate internalities, it's understandable why the properties have to be virtual (those will be read/written through a proxy class), but... why on earth my entities methods must also be...

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...

Nhibernate Linq Get object by name not by Id

c#,linq,nhibernate
public T FindById(object id) { return session.Get<T>(id); } I want to get object by Name Something like this, but I am not able to write a query with type T session.Get<T>().Where(x => x.something == something).SingleOrDefault(); or is there any alternative to this approach?...

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 {...

Empty association table when trying to save many-to-many relationships between entities

c#,nhibernate,many-to-many,nhibernate-mapping
I have User entities (User mapping file) and Role entities (Role mapping file). I create some Users and Roles, assign roles to users and users to roles, save the whole lot, retrieve a User and test some assumptions (which fail). Here's my test code: [Test] public void TestUsersAndRolesWithoutWrappers() { //Ensure...

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?

Inject ISession into custom valueresolver

nhibernate,asp.net-web-api,dependency-injection,automapper,structuremap
I'm trying to inject an instance of ISession into a custom AutoMapper ValueResolver. Here's the resolver public class ContactTypeResolver : ValueResolver<Common.Models.ContactType, Models.ContactType> { ISession _session; public ContactTypeResolver(ISession session) { _session = session; } protected override Models.ContactType ResolveCore(Common.Models.ContactType source) { return _session.Load<Models.ContactType>(source.Id); } } I have a profile for setting up...

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...

NHibernate hql tuple result

c#,nhibernate
hql = "select f, b from Foo f, Bar b" var resultList = session.CreateQuery(hql).List<object[]>(); result list item is an array where [0] is of type Foo and [1] id of Type Bar Is there a way to use Tuple<Foo,Bar> (or other generic class ) as generic parameter insted of object[]...

NHibernate map one-to-many relationship with intermediate table

c#,nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
How to define mapping without intermediate class PostTag creation? I have three tables t_post(id...) t_tag(id, name) t_post_tag(id,post_id, tag_id) I want to have a collection with Tags in Post type classes: class Post { public virtual IEnumerable<Tag> Tags{ get; set; } } public class Tag { } mappings: <?xml version="1.0" encoding="utf-8"?>...

How do I load columns of a second table as properties on a model in NHibernate?

c#,sql-server,nhibernate
I am trying to load columns from a second table in the database as properties on a model using NHibernate. I'm using an XML mapping file and tried using the join tag. When I build and try to run the code, I get the following error: The element 'join' in...

NHibernate variable limits with SQL 2000

c#,nhibernate,sql-server-2000
I am trying to use the Take method in hibernate with SQL 2000. When doing so, it gives me the error:Dialect does not support variable limits. In searching around I found a way to override the check for variable limit support and set my code up as follows: return Fluently.Configure()...

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...

Nhibernate adding new entry for child object on update

c#,nhibernate
public CaseMap() { Id(c => c.ID);//.GeneratedBy.Increment(); Map(c => c.CIN); Map(c => c.CaseNumber); Map(c => c.Name); Map(c => c.RegistryNumber); References(c => c.ApplicantType).Column("FK_ApplicantTypeId").Cascade.None(); References(c => c.ApplicationType).Column("FK_ApplicationTypeId").Cascade.None(); References(c => c.AVSUser).Column("FK_UserId").Cascade.None(); References(x => x.Program).Column("FK_ProgramId").Cascade.None(); References(c =>...

Convert XML mappings to Code Mapping for ISET of ManyToMany

nhibernate,nhibernate-mapping,hibernate-mapping,mapping-by-code
I am presently working on one of the project, where I need to convert the xml mappings to code mappings. I have a ISET collection with Many to Many along with where clause. I had done the code mappings but where to put the where clause in code mappings ?...

Persisting DateTime when saving/updating entities in fluent nhibernate

c#,nhibernate,timestamp,fluent
I'm trying to persist the datetime of creation and update of entites (not relevent to versioning and concurrency) using fluent nhibernate. To achieve this using nhibernate I would write this mapping tag: <timestamp name="Timestamp" access="property" unsaved-value="null" /> How can I make fluent nhiberbate generate that mapping tag?...

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...

Encountering an “undefined alias or unknown mapping” exception when using NHibernate's Multi Query feature

c#,nhibernate,nhibernate-mapping
I am trying to implement a NHibernate's Multi Query feature for a typical Paging and Counting functionality using NHibernate version v2.0.50727. I've been following the example given here by Ayende Rahien and my code is a lot similar to it. However, every time it hits the call to return the...

NHibernate asks hibernate.cfg.xml even if web.config configured

asp.net,asp.net-mvc,nhibernate,asp.net-mvc-5,nhibernate-mapping
this is ASP.NET MVC 5 Sample App. trying to learn MVC's module NHibernate. if I understand right. hibernate.cfg.xml file is not neccessary if settings coded in web.config as a configsection. is xmlns version is wrong ? or do you see something misspelled ? so why NHibernate asks hibernate.cfg.xml even if...

Entity Framework with mutliple database servers

c#,entity-framework,nhibernate,multi-database
Today we're developing a solution for Windows environments with SQL Server CE and Entity Framework 6.13 as ORM (Code First). However we're studying the availability to port it to Linux environments and, of course, as Linux doesn't support SQL Server databases, we intend to use SQLite on Linux machines and...

System.Configuration.ConfigurationErrorsException occurred Error creating context 'spring.root' — InnerException: Client.OracleException

c#,spring,oracle,nhibernate
Presently, I am attempting to debug a web application that connects to an oracle database. When I run the application, I receive the following error: System.Configuration.ConfigurationErrorsException occurred HResult=-2146232062 Message=Error creating context 'spring.root': Source=System.Configuration BareMessage=Error creating context 'spring.root': Line=0 StackTrace: at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord,...

NHibernate 3.2 - Pre and Post Delete event listeners not invoked

c#,nhibernate
I am working against an implementation of NHibernate 3.2 with several custom entity state change listeners: PreDelete, Delete, and PostDelete. The DeleteEventListener is defined by inheriting a custom type from DefaultDeleteEventListener, but the others are simply implementing the IEventListener interfaces. The body of the CustomDeleteEventListener follows: protected override void DeleteEntity(IEventSource...

Date column not being persisted for dates before the year 1753 [duplicate]

c#,sql-server,nhibernate
This question already has an answer here: Fluent NHibernate Problems with SQL Server 2008 DATE Column Values 2 answers I'm trying to persist an entity using NHibernate, but my DateTime? property is not being persisted for dates before 1753. I'm aware of the fact that this is DATETIME's lower...

Nhibernate dialect, precision for Casting decimal from 5 places to 2 places

nhibernate
We have a currency field in database of type decimal(20,5). How do I add a CAST or COnvert to the outgoing Nhibernate criterion? SELECT TOP (1000) this_.DepositAccountId as DepositA1_71_0_, this_.BranchId as BranchId71_0_, this_.ConfigurationStatusId as Configu14_71_0_, this_.ConfiguredBy as Configu41_71_0_, this_.ConfiguredDate as Configu15_71_0_, this_.DepositAccountBalance as DepositA9_71_0_ FROM dbo.DepositAccount this_ WHERE Convert(Decimal(20,2), this_.DepositAccountBalance)...

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...

Not persister M:N with association class in NHibernate?

.net,nhibernate,nhibernate-mapping
I want to map a M:N asociation betwen Products and Cart with asociation class ProductsOfCart betwen them. However data is not persister but I dont know why can you help me? Here is a code from CartControler Create(); Product productD = new ProductDao().GetById(product); ProductsOfCart productsOfCart = new ProductsOfCart(); User user...

Nhibernate exception: base {NHibernate.HibernateException} = {“illegal access to loading collection”}

c#,asp.net,asp.net-mvc,nhibernate,nhibernate-mapping
I am working on an NHibernate exception :"base {NHibernate.HibernateException} = {"illegal access to loading collection"}" Table PatRef is Parent table. Table PatCon is Sub table. When I retrieve data from PatRef to PatCons at debuging mode, the error message screen shot is below. The Nhibernate data mapping screenshots are below....

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...

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...

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...

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....

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...

NHibernate QueryOver NullReferenceException

c#,nhibernate,nhibernate-queryover
I have following QueryOver which throws NullReferenceException when newExam.ActiveTo is null (ActiveTo type is DateTime?) Exam examAlias = null; examsInSameTime = session.QueryOver(() => examAlias) .Where(() => examAlias.ActiveTo == null && newExam.ActiveTo == null) .Future<Exam>(); When I rewrote query to this HQL everything works fine var query = "from Exam exam...

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>...

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...

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...

Conflicted with the REFERENCE constraint. How to solve this?

asp.net-mvc-4,nhibernate
I catch this GenericADOException exception but some unexpected exception comes again when I do genRep.Update(userW). How can I fix this problem? This is my code: public ActionResult DeleteUser(long? UserID) { GenericRepositoryV2 genRep ; if (!SecurityService.IsLoggedIn(Session)) { return SecurityService.LoginAndRedirect(Request); } try { genRep = new GenericRepositoryV2(); genRep.StartTransaction(); User user = genRep.GetById<User>(UserID);...

SetUp : Spring.Objects.Factory.ObjectDefinitionStoreException : Error registering object with name 'NHibernateSessionFactory' defined in 'assembly

nhibernate,nunit,nhibernate-mapping,spring.net
When I run a unit test, this is the error I'm getting: SetUp : Spring.Objects.Factory.ObjectDefinitionStoreException : Error registering object with name 'NHibernateSessionFactory' defined in 'assembly [Eiq.Middleware.Data.DomainRepository, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5c61376b85e43767], resource [Eiq.Middleware.Data.DomainRepository.Persistence.xml] line 15' : Could not resolve placeholder 'TDM.providerName'. at...

Like doesn't escape special characters NHibernate

c#,sql,linq,nhibernate
I have a problem with NHibernate LINQ contains method, because I want to escape special characters in the string for example if I type: lel%lel I want to find exactly lel%lel but not lel4325234534lel To find values I use following methods: tabArray = _session.Query<Tab>() .Where(x => x.attr.Contains(query)) .ToArray(); I also...

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...

Is NHibernate generated SQL slower than handwritten statements in SP nowadays?

sql-server,nhibernate,sql-server-performance
I wonder about the general performance with insertions/updates/deletes in a sql server 2012 db, with data amounts sometimes reaching 20 m. rows in a table. Can I trust NHibernate in generating optimal queries?...

Nhibernate sessionPerThread

c#,nhibernate,concurrency,castle-windsor
I am creating entities in with multiple thread at the same time. When i do this in sequence order (with one thread) everything is fine, but when i introduce concurrency there are pretty much always new exception. i call this method asynchronously: public void SaveNewData(){ ....DO SOME HARD WORK.... var...

Sort by count HQL

java,sql,hibernate,nhibernate,hql
I'm trying to sort Schools by the number of Students. There is a ManyToOne / OneToMany relationship between them. This is not working but this is what I have so far from School s order by count(s.students) I would prefer not to use Criteria as I would have to refactor...

NHibernate trying to update ID to null on a delete operation

c#,xml,visual-studio-2010,nhibernate
At first I have these entities: Persona, Paciente, Alergia, Cita and Consulta. The problem comes when I try to delete a Persona. My DB looks like this: I'm currently just working with Persona and Paciente. And those are their mapping and classes: <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping assembly="Odontologia General Admin" namespace="Odontologia_General_Admin.Persistence.Entidades"...

By code mapping of many-to-many with OrderBy

nhibernate,nhibernate-mapping,mapping-by-code
I'm using by code mappings and trying to map a manytomany. This works fine but I need OrderBy for the child collection items. I noticed this has been omitted (it does exist in the HBM mappings). e.g. public class Mapping : EntityMapper<Category> { public Mapping() { Set(x => x.Items, m...

nHibernate Subquery-WhereAll displays “not a delegate type”-error

c#,sql,nhibernate
I am trying to create a nHibernate-Query with a subquery following this blog-entry. My working SQL looks like this: SELECT * FROM Product WHERE Id IN ( SELECT p.Id FROM Product AS p INNER JOIN ProductSupplier AS ps ON ps.ProductId LIKE p.Id WHERE ps.SupplierProductNumber LIKE '102.02-7100' GROUP BY p.Id );...

Deeper fetch in nHibernate returns a proxy object

c#,nhibernate,proxy
I have the following data model that i'm trying to fetch using nHibernate. Author -> List of AuthorBook -> Book AuthorBook is basically a junction table that allows the many to many mappings between Author and Book. Basically, I'm trying to come up with a query (using one session) that...

How do I return a generic list with QueryOver

c#,.net,generics,nhibernate,queryover
I'm trying to do a simple select with queryover and get a generic list. I want to get from the table only username, email and firstname and omit the rest. This is my code: public IList<Users> GetAllByRole(string role) { var users= this.Session.QueryOver<Users>() .where(f => f.role == role) .select(f => f.username)...

Castle Windsor / ActiveRecord / NHibernate: How to intercept/modify connection string

c#,nhibernate,connection-string,castle-windsor,castle-activerecord
I have consolidated the connection string information for a number of C# .NET solutions that are in my possession. Previously, each project was storing its connection string in its own format, requiring me to modify several files for each installation of the software. Only one remaining solution is giving me...

using QueryOver's query seperated

c#,nhibernate
How can I use QueryOver's linq query seperated like below ICriteria which will be used in a generic method? ICriterion c = Restrictions.And(Restrictions.Eq("Name", "Foo"), Restrictions.Or(Restrictions.Gt("Age", 21), Restrictions.Eq("HasCar",true))); IQueryOver<Foo> c = session.QueryOver<Foo>().Where((k => k.Name == "Tiddles" && k => k.Age== 21) || k => k.Age < 21); public static IList<T> All(ICriterion...

Unable to create one-to-one relationship between entities

c#,nhibernate,orm,nhibernate-mapping
Update 1: Added a link to the code for the entity classes. I have a Vehicle entity (to hold information about a vehicle) and an UploadedDocument entity (represents any uploaded document, in this case (say) the registration papers) being stored in the DB in separate tables (other entities may also...

QueryOver OrderBy child property using strings

nhibernate,nhibernate-queryover
I'm struggling with using QueryOver.OrderBy with strings for property names on child entities. e.g. the following works but I am hardcoding the OrderBy field. Customer custAlias = null; session.QueryOver<Campaign>() .JoinAlias(x => x.Customer, () => custAlias) .OrderBy(() => custAlias.Name).Desc() // want to use string property name .List(); I can specify the...

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...

What does Future() means in NHibernate?

c#,nhibernate,future
I'm new to NHibernate the description for IEnumerable Future(); says the following // Summary: // Get a enumerable that when enumerated will execute a batch of queries in // a single database roundtrip Just wondering what does it means, the description has nothing to do with the word 'future'...

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 one to many relationship error

c#,mysql,nhibernate,nhibernate-mapping
I am encountering foreign key error while saving child record for parent-child relationship in nhibernate. I am using Mysql as the database. Value of foreign key column inserted is "0" Table CREATE TABLE Company( Id INT NOT NULL AUTO_INCREMENT, Name Varchar(100) NOT NULL, PRIMARY KEY (Id) ); CREATE TABLE Client(...

How to use Log4net to log in File in Windows Application

c#,nhibernate,log4net
I'm trying to use Log4net for the first time in my WinForm application, before that I thought to see if it works in my Console application which didn't even produce any log file. I have referred other posts as well to achieve logging but to no avail. To get NHibernate...

Minimal and correct way to map one-to-many with NHibernate

c#,nhibernate,orm,nhibernate-mapping
I am new to NHibernate and C#, so please be gentle! I have the following two NHibernate entities: Employee { private long _id; private String _name; private String _empNumber; private IList<Address> _addresses; //Properties... } and Address { private long _id; private String _addrLine1; private String _addrLine2; private String _city; private...

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...

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...

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...

Modern ORM vs Repository/IoW pattern

entity-framework,nhibernate,orm,repository-pattern,unit-of-work
I read a lots of content about the usage of Entity Framework/NHibernate (or basically any other modern ORM) with the repository/UnitOfWork patterns. Apparently the community is divided. Some would say the repository pattern is almost mandatory, some others would say that it's a waste of time... Well, I come up...

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...

Nhibernate queryover filter based on count of child collection

sql,nhibernate,nhibernate-queryover,nhibernate-projections
Ultimately I want to filter all parent objects that have less than 2 children. I'm building a search screen with a grid dashboard, which uses the following logic as a example of how to build a query. var query = Session.QueryOver<Parent>(() => parentAlias); if (!string.IsNullOrWhiteSpace(SearchCriteria.OpenedBy)) query.Where(Restrictions.Eq(Projections.Property<Parent>(x => x.OpenedBy), SearchCriteria.OpenedBy)); if...

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...

Nhibernate translates 1=0

c#,nhibernate
What causes this 1=0 in Nhibernate SELECT this_.LoanId as LoanId89_0_, this_.BranchId as BranchId89_0_, FROM dbo.Loan this_ WHERE this_.LoanId in ( SELECT this_0_.LoanId as y0_ FROM dbo.MyEntity this_0_ WHERE this_0_.MyEntityId = 795 ) and 1=0 ORDER BY this_.LoanNumber asc; I am trying to retrieve some records and Nhibernate translates it to...

nHibernate - Dynamic projection list, need to return constant text

nhibernate,nhibernate-projections
How can I return constant text in projection list, Not sure if I am doing it right or not. projectionList.Add(Projections.Property("This Year Issue Price").WithAlias(() => sProduct.PriceTitle)); This way I assume that I will get "This Year Issue Price" as columns value for PriceTitle. Doing it because this is dynamic and could...

NHibernate Filtered Child Collection Lazy Loaded even with eager fetch specified

c#,nhibernate,nhibernate-criteria
Im trying to find out why a child collection is being returned without filtering even when eager loading the collection and the generated SQL is correct. The fluent mappings for the classes are: public class OptionIdentifierMap : ClassMap<OptionIdentifier> { public OptionIdentifierMap() : base("OptionIdentifier") { //Id Mapping Removed HasMany<OptionPrice>(x => x.OptionPrices)...

could not delete collection : [NHibernate.Exceptions.GenericADOException]

c#,hibernate,nhibernate,hbm
I have Two Table , tableA and tableB. tableA have column : tabAId, col2, col3 (tabAId primaryKey and Identity column.) tableB have column : tabAId, name (tabAId is not null) I have create Bag in hbm file of tableA, to maintain relation ship. <bag name="tableB" lazy="true" inverse="false" batch-size="25" cascade="all-delete-orphan"> <key...

Override lazy loading behavior 'lazy=false'

nhibernate,criteria,criteria-api,queryover,nhibernate-queryover
I would like to override the default lazy loading behavior which is set in mappings as 'lazy=false'. Can't change it as many parts of existing application depend on this setting. After spent some hours on it I didn't find a solution so I'm asking here. How to do this? What...