Menu
  • HOME
  • TAGS

NHibernate map one-to-many relationship with intermediate table

c#,nhibernate,nhibernate-mapping,fluent-nhibernate-mapping

To map pairing table, without explicit Entity representing it, we have to use <many-to-many>. Also attribute table="..." must be present - to instruct NHibernate about that pairing table. (In case, that we assign Tags into Posts, we should not mark such mapping as inverse) <bag name="Tags" table="t_post_tag" lazy="true" cascade="none" inverse="true">...

Sort by count HQL

java,sql,hibernate,nhibernate,hql

Ok I figured it out. This worked from School s order by size(s.students) As per the Hibernate documentation You can test the size of a collection with the special property size or the special size() function. ...

Override lazy loading behavior 'lazy=false'

nhibernate,criteria,criteria-api,queryover,nhibernate-queryover

We cannot override mapping in this case. We can do it opposite way - have lazy in place - and use eager fetching for querying. The decision process (of reference loading) is done outside of the query, ex post. So it could be pre-loaded, but cannot be avoided. Solution here...

using QueryOver's query seperated

c#,nhibernate

The equivalent to the first line, in lambda form is ICriterion cr = Restrictions.Where<Foo>(k => k.Name == "Foo" && (k.Age > 21 || k.HasCar)); ...

NHibernate - Add new property to class

nhibernate

In general, we can use configuration setting for updating our DB schema whenever ISessionFactory is created: <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="hbm2ddl.auto">Update</property> Check Table 3.2. NHibernate Configuration Properties We can do it even in our own code: How to update database table schemas with NHibernate schema generation? (snippet from Q &...

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

nhibernate

So here's what should work (I've greatly simplified the query, but the problems are all the same): IType decimalType = TypeFactory.Basic("decimal(20,2)"); IProjection castProjection = Projections.Cast( decimalType, Projections.Property<DepositAccount>(acct => acct.DepositAccountBalance)); var accounts = session.QueryOver<DepositAccount>() .Where(Restrictions.Eq(castProjection, 1.01)) .List<DepositAccount>(); Unfortunately this generates the following SQL: SELECT this_.* FROM DepositAccount this_ WHERE cast(...

Nhibernate adding new entry for child object on update

c#,nhibernate

There was code error Instead of cCase.Address = new CaseAddress(); cCase.Address.Street = record.ResidenceStreet; It should have been just cCase.Address.Street = record.ResidenceStreet; cCase.Address = new CaseAddress() was creating a new object for CaseAddress result in new entry. Also the update method should be session.Merge instead of update public bool Update(T persistableEntity)...

NHibernate hql tuple result

c#,nhibernate

Yes you can, something like: // The new Tuple<Foo, Bar>(foo, bar) constructor Type constructor = typeof(Tuple<Foo, Bar>).GetConstructors()[0]; and then .SetResultTransformer(Transformers.AliasToBeanConstructor(constructor)); before the .List() addendum I've looked at my code (because I've already done this one or two years ago :) ), and I noticed that I preferred Type constructor =...

IQueryable Where only class name is known

c#,linq,nhibernate,linq-query-syntax

Generic parameters are compile type construct. In your case you specify a string (runtine entity) as a type name, so you need to create a closed generic method instance at runtime via reflection. Next code demonstrates this: Suppose I have: public void Query<T>() { Console.WriteLine("Called Query with type: {0}", typeof(T).Name);...

QueryOver OrderBy child property using strings

nhibernate,nhibernate-queryover

The alias used is the name of the variable. So Projections.Property("custAlias.DOB") (can't test now, but if I remember corretly it works) Interestingly, it isn't the variable, in itself, that is used as the alias, but its name. What does it means? QueryOver<Campaign> query; { Customer custAlias = null; query =...

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

c#,nhibernate,many-to-many,nhibernate-mapping

Your mapping seems to be correct. Just not sure what is the session default FlushMode. To be sure, that it is not None, try to append into first using the session.Flush();. using (ISession session = NHibernateHelper.OpenSession()) { ... session.Flush(); } Reason why simple insert into User and Role is happening...

Nhibernate sessionPerThread

c#,nhibernate,concurrency,castle-windsor

So i researched and it seems that NHibernateIntengrationFacility doesnt support this transaction management out of the box. I solved it when i changed to new Castle.NHibernate.Facility which supersede Castle.NHibernateIntegration - please note that this is only beta version currently. Castle.Nhibernate.Facility supports session-per-transaction management, so it solved my problem completely....

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

c#,asp.net,asp.net-mvc,nhibernate,nhibernate-mapping

The issue caused by:"a boolean field in your Project class may be marked as a varchar field in the database". I have a database column "ON_DIALYSIS" "VARCHAR2(1)", it was mapping as a bool in mapping class PatCon public virtual bool OnDialysis { get { return _onDialysis; } set { _onDialysis...

FluentNhibernate: Query to retrieve distinct values

c#,linq,nhibernate,fluent-nhibernate

In both examples from Brenda are missing the transformation. Disclaimer: Check first if the types are correct in the DTO or in the Linq projection. public class MyDto { public string Corporation { get; set; } public DateTime? CalculationDate { get; set; } public string ValuationRule { get; set; }...

Fluent Nhibernate mappings / Join

c#,nhibernate,fluent-nhibernate

How about altering data model ? It seems that Staff is always in a given Position collection at the given Company level. This suggest following model public partial class Staff { public virtual IEnumerable<CompanyPosition> Positions { get; protected set; } } public class Position { //... } public class Company...

NHibernate : No update with composite key

c#,nhibernate,fluent-nhibernate

I. PERSISTING, executing sql write command as discussed in the comments, the first thing we need to make that all happened is to extend the our code with a ISession.Flush() 9.6. Flush (some cite) ... Except when you explicity Flush(), there are absolutely no guarantees about when the Session executes...

Bi-directional relationship in nhibernate 4.0

c#,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping

I found the fix for the problem: The fix for the problem is to add Inverse to the mapping of the parent file. So, the mapping for Department will be: DepartmentMap : ClassMap<Department> { Table("...."); HasMany(x => x.Employees).KeyColumn("DeptId").Inverse().Not.KeyNullable(); } ...

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

c#,.net,nhibernate,fluent-nhibernate,nhibernate-configuration

I wish to have the answer, but mine is: no. We have to pass this values as a setting. The reason is the way how is the table hi-lo generator implemented. Check the TableHiLoGenerator code .Configure() /// <summary> /// Configures the TableHiLoGenerator by reading the value of <c>table</c>, /// <c>column</c>,...

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

This turned out to be as I expected a mapping issue but it was really hard to find. The issue was with the related properties: public virtual CnSubGroup CnSubGroupOut { get; set; } public virtual CnSubGroup CnSubGroupIn { get; set; } The CnSubGroup entity also has a version mapping and...

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

c#,nhibernate,db2,nhibernate-mapping,nhibernate-4

That error doesn't seems to be connected to problems with the foreign keys. It seems to be that the NHibernate can't find the XML files. The "common" problems are normally three: The XML files must be set (in their Properties) with the Build Action = Embedded Resource In the configuration...

How to specify Schema for Lists while mapping Nhibernate by code

nhibernate,nhibernate-mapping

I have never used mapping by code, but i assume this is the solution: List(x => x.Students, l => { l.Where("deleted = 0"); l.Key(k => { k.Column("post_id"); k.NotNullable(true); }); l.Schema(Constants.DatabaseSchemaNames.Article); l.Table("tag_post"); }, x => { x.ManyToMany(m => m.Column("tag_id")); }); ...

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

c#,sql,nhibernate

I don't think you should be using WhereAll in this case. Does this work: query.WithSubquery.WhereProperty(p => p.Id) .In(QueryOver.Of<Product>() .JoinAlias(x => x.Suppliers, () => productSupplierAlias) .Where(() => productSupplierAlias.Product.Id == productAlias.Id) .Where(() => productSupplierAlias.SupplierProductNumber == searchtext) .Select(p => p.Id) ); ...

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

c#,spring,oracle,nhibernate

The way I stopped getting the above exception was to uninstall TeamCity and remove my application's website from IIS Manager. To be clear, I don't think the problem was with TeamCity--the problem was that I ran a build to deploy my application, which added the website to IIS and caused...

NHibernate - SafeHandle Cannot be Null

c#,nhibernate,oracle11g,fluent-nhibernate

It turns out that it was the visual studio 2015 preview that was somehow messing up something related to oracle libraries which led to this error. I had to reformat my pc couple of times until I understood whats going on.

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

hibernate,nhibernate,fluent-nhibernate,informix,informixdb

After studies in the customer environment and logs it was found that the error occurred due to completion of a backup in a certain schedule that caused instability in the bank resulting in connection error and after that the the application did not work properly need to be restarted (the...

Nhibernate and like statement on XML field

nhibernate

In case, that we do not need .Query() (LINQ), and we can use Criteria query or QueryOver, we can use conversion: // the projection of the column with xml // casted to nvarchar var projection = Projections .Cast(NHibernateUtil.StringClob , Projections.Property("thatXmlFieldWhichIsMappedAsString")); // criteria filtering with LIKE var criteria = Restrictions.Like(projection, "searched...

How to use Log4net to log in File in Windows Application

c#,nhibernate,log4net

I removed this from AssemblyInfo.cs: [assembly: log4net.Config.XmlConfigurator(Watch = true)] And added the following just before creating Configuration instance: log4net.Config.XmlConfigurator.Configure(); var cfg = new Configuration(); // creating Configuration instance And it created the folder containing log file. I even changed attribute: <appendToFile value="false" to <appendToFile value="true" so that file will not...

NHibernate 3.2 - Pre and Post Delete event listeners not invoked

c#,nhibernate

From what I understand, the OnDelete, OnUpdate, ... are used to do things like validation, or modify the actual entity being deleted, updated, inserted. This occurs pretty much at the start of the pipeline, see e.g. "NHibernate interceptor magic tricks, pt. 4" When a delete occurres, the very first thing...

Could not resolve property on KeyColumn

c#,nhibernate,fluent-nhibernate

Based on the Exception I would say, that we can face this issue in case - that the calling side looks like this: var list = ByParameter<MenuItem>("ParentId", 123); And because the snippet above does not show that class MenuItem contains ValueType (non-reference) property ParentId: public class MenuItem { // the...

Inject ISession into custom valueresolver

nhibernate,asp.net-web-api,dependency-injection,automapper,structuremap

I believe @RadimKöhler is right. Your parent container (where the AutoMapper types are configured) doesn't have access to the plugin types defined in the nested container. It just doesn't know about the ISession plugin type hence the exception you get. I can think of a couple solutions here. DISCLAIMER I...

NHibernate delete child from parent collection with delete cascade

c#,nhibernate,fluent-nhibernate

Manual deletion of the collection items is not a solution. It in facts breaks the cascading feature. In case we do have mapping Cascade.AllDeleteOrphan(), we should expect that deletion of Parent will deleted Children as well - no need to do more then delete Parent. Just ... NHibernate does not...

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

asp.net,asp.net-mvc,nhibernate,asp.net-mvc-5,nhibernate-mapping

found the answer. it seems scheme key is changed in new nhibernate version changed <hibernate-configuration xmlns="urn:nhibernate-configuration-version-2.2"> to <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> fixes the problem. Im sure because I retested back the first scheme. and boM! same error throw. so xmlns string is updated. how I found it. opened web.config>xml in menu>Schemes [added...

NHibernate query performance with a large number of disjunctions and conjunctions

c#,sql,hibernate,nhibernate

As pointed out in the comments, this is more of a SQL query issue than an NHibernate one. I resolved it by improving the logic of the full query to minimise the number of disjunctions and conjunctions produced.

NHibernate SchemaExport.Execute does not create table

c#,nhibernate,nunit,nhibernate-configuration

I would suggest to use full path in the connection string: // instead of this <property name="connection.connection_string" >Data Source=MyFirstNHibernateProject.sdf</property> // we should use <property name="connection.connection_string" >Data Source=C:\MyFirstNHibernateProject\MyFirstNHibernateProject.sdf</property> Where the "C:\MyFirstNHibernateProject\" should be the full path to the "MyFirstNHibernateProject.sdf" Also, in case you are suing CE 4.0 I would suggest to...

What does Future() means in NHibernate?

c#,nhibernate,future

Future allows to execute two or more sql in a single roundtrip, as long as the database supports it. It's also almost transparent, so you'll want to use Futures whenever possible. If NHibernate can't execute the queries in a single roundtrip, it will execute the queries in two or more,...

NHibernate QueryOver NullReferenceException

c#,nhibernate,nhibernate-queryover

I would say, that solution here should be surprisingly simple and elegant (but only if I do read your issue correctly). The point is - check your params in C#, do not send that into DB side: Exam examAlias = null; var query = session.QueryOver(() => examAlias); //here we will...

Database field with multiple allowed value types

c#,postgresql,nhibernate,fluent-nhibernate,domain-driven-design

You can use a json (or jsonb if your postgres version supports it). I wouldn't do that in this case. In order to get the best use out of indexes and data searching, it'd be best to come up with a structure that kept the different data types in different...

NHibernate: ProjectionList: Can we create dynamic projectionlist for Orderby

nhibernate,queryover,nhibernate-queryover,nhibernate-projections

I expect, that you experience an issue with generated keyword "AS" inside of the ORDER BY in case, that you pass projections like this: // NHibernate will leave few AS, except the last query.OrderBy(sortProjectionList).Asc(); To avoid that, we can do it like this: // NHibernate will solve each projection separately...

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

nhibernate,oracle11g,fluent-nhibernate,decimal,buffer-overflow

So, what I have figured out is as follows:- Database column is float(126) which has more precision than supported by .NET hence, in some cases exception is thrown when .NET cannot handle the data (overflow). (Oracle number to C# decimal) When a formula is specified in fluent mapping, a column...

SetFetchMode Lazy doesn't overwrite ClassMap settings

c#,nhibernate,fluent-nhibernate,lazy-loading

I have to say, that this is not possible. Our JAVA brother Hibernate (from which NHibernate was ported into .NET) seems to have that option: Hibernate: Enabling lazy fetching in Criteria API But NHibernate does not support that. Chek also Override lazy loading behavior 'lazy=false'. What we can do, is...

Having different automapping “configurations”

c#,nhibernate,fluent-nhibernate,fluent-nhibernate-mapping,automapping

I've found the solution: Conventions.Find allows to find convention instances. var map = AutoMap.AssemblyOf<AutomappingConfiguration>(new AutomappingConfiguration()) .Conventions.AddFromAssemblyOf<AutomappingConfiguration>() .UseOverridesFromAssemblyOf<AutomappingConfiguration>(); foreach (var c in map.Conventions.Find<TableConvention>()) { c.AllWritable = allWritable; } ...

NHibernate Purge/Truncate Table and repopulate in single transaction

.net,nhibernate,fluent-nhibernate

Option 1 session.Clear(); // to get rid associations of the objects in memory session.CreateQuery("delete from MyClass").ExecuteUpdate(); foreach(var entity in CreateNew()) session.Save(entity); Option 2 session.CreateQuery("delete from MyClass where Id not in (:ids)") .SetParameterList("ids", newIds) .ExecuteUpdate(); foreach (var id in newIds) { var entity = session.Get<MyClass>(id); // returns the cached instance if...

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

c#,sql-server,nhibernate

This aproach, would be working only if the root entity (Article) would have composite key: <class name="Article" table="article"> // not and <id> mapping <!--<id name="Id" column="articleID" unsaved-value="-1" type="Int32"> <generator class="identity" /> </id>--> // but <composite-id> <composite-id> <key-property name="Id" column="articleID" ></key-property> <key-property name="PublicNumber" column="articleNum"></key-property> </composite-id> <property...

Deeper fetch in nHibernate returns a proxy object

c#,nhibernate,proxy

Something like this should fetch all your data in one go: AuthorBook authorBooks = null; Book book = null; session.QueryOver<Author>() .Where(x => x.Id = AuthorId) .JoinAlias(a => a.AuthorBooks, () => authorBooks,JoinType.LeftOuterJoin) .JoinAlias(() => authorBooks.Book, () => book) .SingleOrDefault(); ...

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

sql-server,nhibernate,sql-server-performance

The simple answer is: No. NH cannot generate "optimal queries" the way you do with hand written queries. It usually gets data from the database to create objects in memory. So for instance, by default it always selects all columns in a table. It tries to optimize SQL compilation time...

How do I return a generic list with QueryOver

c#,.net,generics,nhibernate,queryover

We need to add 1) aliases to each column and use 2) transformer: // Users u - will serve as an alias source below Users u = null; IList<Users> users = this.Session.QueryOver<Users>() .Where(f => f.role == role) .SelectList(list => list // here we set the alias .Select(p => p.username) .WithAlias(()...

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

c#,sql-server,nhibernate,fluent-nhibernate,hql

The point here is CROSS JOIN if there are no mapped relations, JOIN on existing (mapped) relations. So, in case, there is no mapped relation Question to Answer - we still can query it like this: // instead of INNER JOIN we use 'comma' to produce CROSS JOIN // instead...

Persisting DateTime when saving/updating entities in fluent nhibernate

c#,nhibernate,timestamp,fluent

If you mean map a DateTime property as this: <property name="Timestamp" type="Timestamp"/> This is the equivalent in Fluent NHibernate: Map(x => x.Timestamp).CustomType<TimestampType>(); ...

Nhibernate one to many relationship error

c#,mysql,nhibernate,nhibernate-mapping

The point here is that for both many-to-one and one-to-many we have to use the same column "CompanyId" The Company.hbm.xml <bag name="Clients" table="Client" lazy="false" cascade="all" inverse="true" > <!-- wrong column name, it must be parent reference in a child table --> <!-- <key column="ClientId"></key> --> <key column="CompanyId" /> <one-to-many class="ConsoleApplication1.Client,...

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

c#,nhibernate,orm,nhibernate-mapping

Just few hints, summarizing the most suitable standards I found out when working with NHibernate. 1) If there is a bi-directional reference in persitence (DB column), express it in C# code bi-directional as well. Other words, if a child has reference to parent, parent should have reference to child. public...

NHibernate Filtered Child Collection Lazy Loaded even with eager fetch specified

c#,nhibernate,nhibernate-criteria

I would like to share my approach, maybe not the answer... I. avoid fetching one-to-many (collections) When creating any kind of complex queries (ICriteria, QueryOver) we should use (LEFT) JOIN only on a start schema. I.e. on many-to-one (References() in fluent). That leads to expected row count from the perspective...

Unable to create one-to-one relationship between entities

c#,nhibernate,orm,nhibernate-mapping

Found the correct way to do this: use a <many-to-one> mapping with an added unique constraint: <many-to-one name="Registration" class="UploadedDocument" column="RegistrationID" unique="true" /> For further reference: 5.1.12. one-to-one...

Convert XML mappings to Code Mapping for ISET of ManyToMany

nhibernate,nhibernate-mapping,hibernate-mapping,mapping-by-code

The where should belong to many-to-many as in the xml mapping Set(x => x.SystemRoles, m => { // set mapping }, col => col.ManyToMany(p => { // mapping of the many-to-many p.Column(x => x.Name("PrivilegeId")); p.Where("PrivilegeType = 'SystemRole'"); }) ); But not fully sure, if all features are already supported in...

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

nhibernate,fluent-nhibernate,queryover,nhibernate-queryover

The point here is a difference in our need of paging and its implementation. while we would expect 5 root elements to be returned, the result is converted into 5 rows, 5 selected rows : Some clue could be found in this Q & A: NHibernate QueryOver with Fetch resulting...

Mapping to Date part of Sql DateTime

c#,sql-server,nhibernate,fluent-nhibernate,nhibernate-mapping

The way to go in case we need the skip the mapped relationship mapping (when CROSS JOIN with WHERE clause is needed) we can use HQL (only way, check e.g. here:) How to join Two tables of two non relashinship defined columns using Nhibernate QueryOver Nhibernate QueryOver JoinAlias UnRelated Entity...

NHibernate Criteria Where any element of list property is true

c#,nhibernate,hql,criteria,restrictions

What we would need is Sub-SELECT. This could be achieved with subquery. 15.8. Detached queries and subqueries We can define subquery with DetachedCriteria: var subquery = DetachedCriteria.For<OrderItem>() .Add(Restrictions.Eq("FinalDeliveryIndicator", true)) .SetProjection(Projections.Property("OrderId")); This would later end up as this SQL snippet: (SELECT OrderId FROM OrderItems WHERE FinalDeliveryIndicator = 1 ) And this...

nHibernate - Dynamic projection list, need to return constant text

nhibernate,nhibernate-projections

To return constant, we can use Projections.Constant() methods: // Projections.Property("This Year Issue Price").WithAlias(() => sProduct.PriceTitle) Projections.Constant("This Year Issue Price").WithAlias(() => sProduct.PriceTitle) NOTE: But, there really should be some reason, for this, because we send that value to DB, then recieve it as many times as many records we get. Maybe...

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

c#,hibernate,nhibernate,hbm

There are only two ways how to solve this. 1) do not use inverse="false" <bag name="tableB" lazy="true" inverse="true" // instead of false batch-size="25" cascade="all-delete-orphan"> <key column="tabAId" /> <one-to-many class="tableB" /> </bag> This setting (inverse="true") will instruct NHibernate to directly delete an item from DB. While using inverse="false" will in general...

By code mapping of many-to-many with OrderBy

nhibernate,nhibernate-mapping,mapping-by-code

Replaced the many to many with one to many and introduced an entity that represents the relationship (followed advice from this article). This has the upside of allowing you to map the order-by column as well as other columns, and also solved the issue of restricting the number of items...

Nhibernate Linq Get object by name not by Id

c#,linq,nhibernate

You can use Expression trees and build something like: protected T Get<T, TValue>(string propertyName, TValue value) where T : class { var par = System.Linq.Expressions.Expression.Parameter(typeof(T), "x"); var eq = System.Linq.Expressions.Expression.Equal(System.Linq.Expressions.Expression.Property(par, propertyName), System.Linq.Expressions.Expression.Constant(value)); var lambda = System.Linq.Expressions.Expression.Lambda<Func<T, bool>>(eq, par); return...

NHibernate: Read uncommited columns

c#,sql,nhibernate

If you are wanting to read updates you have made within a transaction these should already be available to you in memory if you are using the same session that is doing the updates. If you however want to read uncommitted rows via another session you will probably have to...

NHibernate trying to update ID to null on a delete operation

c#,xml,visual-studio-2010,nhibernate

Add not-null="true" and update="false" to Paciente collection mapping: <bag name="Paciente" cascade="all-delete-orphan"> <key column="ciPaciente" not-null="true" update="false"/> <one-to-many class="Paciente" /> </bag> Also, probably you want to map the collection as inverse....

Conflicted with the REFERENCE constraint. How to solve this?

asp.net-mvc-4,nhibernate

Judging by that error, your repository is trying to delete the a user from its table but that user is referenced in another table (dbo.Invoices). So you are seeing a foreign key constraint error where you are trying to delete a record who's primary key is referenced in another table...

Speed up the NHibernate SessionFactory create process

nhibernate,fluent-nhibernate,sessionfactory,uptime

Couple of comments that might help you. You can serialise your sessionfactory after its been built. See this blog post for more info. Or Google serialise sessionfactory nhibernate as there are alot of articles If this is a web site then I would always make sure it is spun up...

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

c#,nhibernate,queryover,nhibernate-queryover

Solution here would be to use a bit different interface IQueryOver<Product, Product> For example, we can see how it works in the doc of the 16.5. Aliases: Cat catAlias = null; IQueryOver<Cat,Cat> catQuery = session.QueryOver<Cat>(() => catAlias) .... Check the source code here /// <summary> /// QueryOver&lt;TRoot,TSubType&gt; is an API...

Nhibernate queryover filter based on count of child collection

sql,nhibernate,nhibernate-queryover,nhibernate-projections

You need a subquery... Children childrenAlias = null; var subquery = QueryOver.Of<Children>(() => childrenAlias) .Where(() => childrenAlias.Parent.ID == parentAlias.ID) .ToRowCountQuery(); query.WithSubquery.WhereValue(2).Le(subquery); Note that I don't know how to do Count > 2, so I'm doing 2 <= Count, and there is the possibility that instead of .Where(() => childrenAlias.Parent.ID ==...

Select from Table Valued Function nhibernate

c#,sql-server,nhibernate,hql,user-defined-functions

You won't be able to use RegisterFunction for this. That's for registering scalar functions. However, you can create a named query and execute that instead. That involves a few steps though: Create the named query XML file. This must end in *.hbm.xml. I find it useful to keep the name...

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

c#,c#-4.0,nhibernate

Well, firstly NHibernate is ORM. ... In object-oriented programming, data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be...

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

c#,nhibernate,proxy-object

Detached objects (loaded in one session, and kept as reference) could be re-attached. We can use session.Merge() or session.Lock() 9.4.2. Updating detached objects Many applications need to retrieve an object in one transaction, send it to the UI layer for manipulation, then save the changes in a new transaction.... ......

NHibernate QueryOver CASE WHEN calculate on column value

select,nhibernate,case,queryover

I think this should do the trick: session.QueryOver<MyTable>() .Select( Projections.Group<MyTable>(x => x.Id), Projections.Sum( Projections.Conditional( Restrictions.Eq( Projections.Property<MyTable>(x => x.MyValue), 1), Projections.Property<MyTable>(x => x.Volume), Projections.SqlFunction( new VarArgsSQLFunction("(", "*", ")"), NHibernateUtil.Int32, Projections.Property<MyTable>(x => x.Volume), Projections.Constant(-1))))) .List<object[]>(); As a rule, QueryOver is pretty terrible at...

Fluent NHibernate automap PostGIS geometry type

c#,nhibernate,fluent-nhibernate,postgis

I was finally able to resolve this by defining a custom UserTypeConvention, i.e.: using NetTopologySuite.Geometries; using NHibernate.Spatial.Type; public class PostGisPolygonUserTypeConvention : UserTypeConvention<PostGisGeometryType> { public override void Accept(IAcceptanceCriteria<IPropertyInspector> criteria) { criteria.Expect(c => c.Type == typeof(Polygon)); } public override void Apply(IPropertyInstance instance) { // Have to set CustomType to be able to...

NHibernate - using CreateMultiQuery

c#,nhibernate

So I got this working - using Criteria rather than HQL. The solution was the following. var criteria1 = DetachedCriteria.For<Server>() .Add(Restrictions.Eq("ServerID", s.ServerID)) .SetFetchMode("Adapters", FetchMode.Eager) .CreateCriteria("Adapters", JoinType.LeftOuterJoin); var criteria2 = DetachedCriteria.For<Server>() .Add(Restrictions.Eq("ServerID", s.ServerID)) .SetFetchMode("Configurations", FetchMode.Eager) .CreateCriteria("Configurations", JoinType.LeftOuterJoin); var result = Session.CreateMultiCriteria()...

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

c#,linq,nhibernate,fluent-nhibernate

To solve issue with mixed upper/lower, we can just convert both sides into .ToLower() return Session.Query<Person>() .Where(r => (r.LastName.ToLower().Contains(s.ToLower()) || r.FirstName.ToLower().Contains(s.ToLower()))); Check this link for more details how the NHibernate native InsensitiveLikeExpression.cs is working (for almost every dialect it is doing the same) : NHibernate IsInsensitiveLike treats strings as case...

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

c#,nhibernate,connection-string,castle-windsor,castle-activerecord

I managed to accomplish my intention. It is not ideal, but will work until the code base is rewritten. (I cannot wait to drop the existing code like a bad dream.) Patrick's comment, under my initial question, let me to refine my search criteria, which yielded the thread located here....

NHibernate fluent mapping to an entity property

asp.net-mvc-4,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping

You can use component mapping: Component(x => StoreAddress).ColumnPrefix("StoreAddress"); Component(x => OfficeAddress).ColumnPrefix("OfficeAddress"); Then create a component map for Address type: public class AddressMap : ComponentMap<Address> { public AddressMap() { //map properterties } } ...

fluent nHibernate Restrictions.Not seems not be working properly

c#,nhibernate,fluent-nhibernate

use a subquery to filter out TableA elements having null values in tabB-Items var subquery = QueryOver.Of<TableA>() .JoinQueryOver(tabA => tabA.TableBItems) .Where(tabB => tabB.X == null || tabB.Y == null) .Select(Projections.Id()); var s = Session.QueryOver<TableA>() .Where(tabA => tabA.SomeID == 123 && tabA.SomeNullableDate != null) .WhereRestrictionOn(Projections.Id()).NotIn(subquery) .JoinQueryOver(tabA => tabA.TableBItems) .Where(tabB => tabB.X...

Mapping a Component inside a Component Collection

nhibernate,fluent-nhibernate,domain-driven-design

The only way I managed to move forward (using the private field) was to set a global Access.Field convention. .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Customer>() .Conventions.Add(DefaultAccess.Field()))...

Modern ORM vs Repository/IoW pattern

entity-framework,nhibernate,orm,repository-pattern,unit-of-work

Personally i think your approach is solid. But equally Im surprised you see this approach as very different to the repository / Unit of Work Pattern. Your IService layer is directly comparable to a basic Unit of Work layer combined with a repository layer implemented via an interface. The repository...

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

c#,nhibernate,nhibernate-mapping

You, and Ayende in the link you gave, are creating queries in HQL using the CreateQuery method. This type of NH query must be written against NH entities, which means you must have a proper mapping, i.e. a Sales entity, and then write select count(*) from Sale as Ayende selects...

setting self as createby

nhibernate,fluent-nhibernate

public class User : Auditable { int Id; string Username; } public class Auditable : IAuditable { public virtual int CreatedBy { get; set; } } public class AuditEventListener : IPreInsertEventListener { public bool OnPreInsert(PreInsertEvent @event) { var audit = @event.Entity as IAuditable; if (audit == null) return false; var...

Why NHibernate requires the entities methods to be virtual?

nhibernate

For the same reasons. If your methods are not virtual, then NHibernate would not be able to initialize proxy. Just consider following code: public class A { private int _a; public virtual int A { get { return _a; } set { _a = value; } } public void DoSomethingWithA()...

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

nhibernate,nunit,nhibernate-mapping,spring.net

To resolve the above issue, performed several steps, though I'm not sure specifically which one fixed it: Added reference to NHibernate.Validator, Version=1.3.1.4000 in my test project and NHibernate.Caches.SysCache, Version 3.1.0.4000 Added reference log4net, Version=1.2.10.0 to my test project to print out more diagnostic info Added references to System.Configuration, System.Web.ApplicationServices, and...

Entity Framework with mutliple database servers

c#,entity-framework,nhibernate,multi-database

using NHibernate (with FluentNHibernate) and code it would be like using NHCfg = NHibernate.Cfg; var config = new Configuration().AddMappingsFromAssembly<Entity>(); if (UseSqlCe) { config.SetProperty(NHCfg.Environment.Driver, typeof(SqlCeDriver).AssemblyQualifiedName); config.SetProperty(NHCfg.Environment.Dialect, typeof(SqlCeDialect).AssemblyQualifiedName); } else if (UseSqlite) { config.SetProperty(NHCfg.Environment.Driver, typeof(Sqlite20Driver).AssemblyQualifiedName); config.SetProperty(NHCfg.Environment.Dialect,...

Migrating from Nhibernate to EF6

c#,sql-server,database,entity-framework,nhibernate

If you are choosing to use int keys because of migrating to EF, you actually don't need to change it, and you can keep the existing data, have a look at this. But if you need to move to int keys for some other reason, it's going to be hard...

Automapper and NHibernate: lazy loading

c#,nhibernate,fluent-nhibernate,automapper

You must add a condition to validate if the collection is initialized to be mapped. You can read here more details: Automapper: Ignore on condition of. AutoMapper.Mapper.CreateMap<DictionaryEntity, DictionaryDto>() .ForMember(dest => dest.DictionaryRecord, opt => opt.Condition(source => NHibernateUtil.IsInitialized(source.DictionaryRecord))); ...

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

c#,nhibernate,fluent-nhibernate,multi-tenant,fluent-nhibernate-mapping

Not tested, but you can set in the SessionFactory (technically in its configuration) the default schema name. The property is hibernate.default_schema. So you could have multiple SessionFactory, one for each schema. Clearly you mustn't set the scema name at the Entity level. Something like: var config = new Configuration(); ......

NHibernate - NonUniqueObjectException

nhibernate,fluent-nhibernate

It turns out that it was a scoping issue. I had to change the code to the following to the following: Category category = null; using(var lifetime = container.BeginLifetimeScope()) { ICategoryRepository categoryRepository = lifetime.Resolve<ICategoryRepository>(); DefaultCommandBus commandBus = lifetime.Resolve<DefaultCommandBus>(); IMappingEngine mapper = lifetime.Resolve<IMappingEngine>(); category = categoryRepository.Get(x => x.Title == "Updated Category...

Fluent Nhibernate - configure all dates to be rehydrated from UTC

datetime,nhibernate,configuration,fluent-nhibernate,utc

The way with fluent NHibernate is Convention Conventions James Gregory edited this page on 3 Apr 2012 · 1 revision ... The conventions are built using a set of interfaces and base classes that each define a single method, Apply, with varying parameters based on the kind of convention you're...

Like doesn't escape special characters NHibernate

c#,sql,linq,nhibernate

I would say, that this should be up to us (our code) not NHibernate. We can use this: How do I escape a percentage sign in T-SQL? i.e. replace any % in C# with [%] lel[%]lel And this would return what expected .Where(x => x.attr.Contains(query)) // query == "lel[%]lel" ...

Fluent NHibernate Join mapping to Joined table

c#,oracle,nhibernate,fluent-nhibernate

I guess that we should change the select. It should not be using the current table DOCLIST (which is alreaedy used for mapping the root class Doc .. Table("DOCLIST")) // current select (SELECT Distinct A.CODE FROM DOCLIST D Left Join DOCSLINKS DL On DL.TODOC_ID=D.DOC_ID Left Join ARTICLES A On DL.ART_ID=A.ART_ID...