Nhibernate How can I express this in HQL

I've been stuck with this query for some time now. The SQL returns the result that I want, but I cannot work out how to express the query in HQL. Here's the SQL: select thread.ThreadId, thread.Title, thread.CreatedOn, thread.ViewCount, thread.CreatedBy, thread.ForumId from Threads thread where (thread.ThreadId in(select post.ThreadId from Posts post where (post.CreatedBy=2 ))) AND (2!=(select TOP 1 post2.CreatedBy

NHibernate Not Exposing Columns in Set CollectionMappings

We are in the process of writing code to generate check constraints with all valid values from our enumeration mappings. Some of our enumerations are inside composite-elements through mapped set collections (see below): <set name="Addresses" table="[Addresses$]" access="field.camelcase-underscore"> <key column="Person" /> <composite-element class="Address"> <property name="StreetAddress1" column="[Street Address 1]" /> <property name="Country"

Nhibernate How to a write a Criteria query with multiple joins involved

I'm trying to code the following HQL query using the Criteria API: var userList = _session .CreateQuery("select u from User u where u.Role.ID=3 and u.Customer.ID=:cID") .SetInt32("cID", 1) .List<User>(); (3 NHibernate objects : User(ID, Name, Role, Customer), Role(ID, Name) and Customer(ID, Name). I tried the following but it doesn't work because NHibernate tries to find a Customer associated with a Role: var userList = _session

NHibernate Fluent vs. Attributes

I'm interested in moving some NHibernate configurations/mappings into the code to help with some maintenance issues. Can anyone provide any advice/pros/cons/comparisons of Fluent NHibernate vs. NHibernate.Mapping.Attributes? I have some experience with Java Hibernate annotations, which I liked, but I'm curious if the NHibernate attributes are comparable, and whether Fluent provides any major upsides/downsides that should be considered.

Fluent NHibernate executes single-row-selects on thousands of objects to link to parents

The following is a simplification of my problem domain. We have a series of Trades, that each gets a record in Valuations every business day. We filter our Valuations List used for a specific day, but to populate the Trade against each of the Valuation rows, NHibernate fires single row selects on the Trades table for around 50k rows in the valuation table. How can I change this so NHibernate does a single select on the Trade table? CREATE TABLE Trades ( TradeId INT , InstrumentType

Fluent NHibernate HasMany not updating the FK

I'm using latest Fluent NHibernate lib ( and I have a problem with saving child entitites. I think this is rather common scenario... I've got a parent with mapping: HasMany<Packet>(x => x.Packets) .Cascade.All() .KeyColumnNames.Add("OrderId"); and a simple Packet class that (in a domain model and FNH mapping) doesn't have any reference to the parent. What gets generated is a correct Packets table that contains a column named OrderId. What doesn't wo

Projecting aggregates together with Entity using NHibernate

I have a pretty standard Orders table and an associated OrderRows table, say: Orders [id] INTEGER [name] ... OrderRows [orderId] INTEGER [quantity] INTEGER [unitPrice] SMALLMONEY [description] VARCHAR(...) For some situations I would like to retrieve a list of Orders together with a summary of totals, most of the time I don't care for the summary. Using the Criteria API I can create a projection of [quantity]*[unitPrice] for each Order but how do I get both the Order and the projection in t

NHibernate queries return multiple copies of the target objects

I have two classes mapped in NHibernate: Dragon and its subclass FierceDragon, with a few FierceDragons stored stored in a table called Dragons. When I run an HQL query like from Dragon... I get back two objects per row: the expected FierceDragon and an ordinary Dragon that's a copy of the FierceDragon (insofar as is possible; naturally it lacks the FierceDragon's extra Ferocity and TimeSinceLastMeal properties). In particular, their IDs are identical. When I do from FierceDragon I get only F

Nhibernate entity with multiple Many-To-Many lists of the same type?

Does anybody know how I would map an entity with two many-to-many collections of the same child type. My database structure is this.... The "normal" relationship will be.... tbl_Parent col_Parent_ID tbl_Parent_Child_Xref col_Parent_ID col_Child_ID tbl_Child col_Child_ID The alternative relationship is... tbl_Parent col_Parent_ID tbl_Include_ParentChild_Xref col_Parent_ID col_Child_ID tbl_Child col_Child_ID The entity and mapping look like this... public par

NHibernate L2 Cache - fluent nHibernate configuration

I've managed to configure the L2 cache for Get\Load in FHN, but it's not working for queries configured using the ICriteria interface - it doesn't cache the results from these queries. Does anyone know why? The configurations are as follows: ICriteria: return unitOfWork .CurrentSession .CreateCriteria(typeof(Country)) .SetCacheable(true); Entity Mapping: public sealed class CountryMap : ClassMap<Country>, IMap { public CountryMap() { Table("C

NHibernate mapping of one class containing 2 references to the same entity

I have a person class, then have a family class where I have a property Father and a property Mother of type Person. I have a database table for Person and a Family table containing FamilyId, FatherId, MotherId where FatherId and MotherId is foreign keys for PersonId in Person table. How would you go about to map this in NHibernate?

Nhibernate: Don't fetch when accessing a child objects primary key

Is there a way in NHibernate to get the foreign key of a child object, without fetching the child object? EG. I have User and UserRole. Can I access User.UserRole.UserRoleId without causing another hit on the database to retrieve UserRole? I realize I can set fetch mode to eager and this will stop it from hitting the database again, but theoretically this shouldn't be needed, as the User table has UserRoldId in it. Thanks in advance.

nhibernate criteria - table name has double quotes

I am using Fluent NHibernate in my application. I have a criteria query that looks like this - var query = DetachedCriteria .For<table2>() .SetProjection(Projections.Distinct(Projections.Property("id"))) //.Add(Restrictions.Between("date_field", startDate, endDate)) .Add(Restrictions.Eq("id", 204010)); Add(Subqueries.In("id", query)); This errors out with the error - NHibernate.ADOException was unhandled Mes

Nhibernate Where to put object-oriented queries in a layered architecture?

Into which layer should you put the object-oriented queries? My thoughts: I think putting them into the presentation layer will usually make no sense. But I don't know whether to put them into business or data layer. Example (NHibernate): Say your business logic needs some method GetCustomersPossiblyInterestedIn(Product p). You might then create a complex HQL query that selects customer objects where the customer has already bought a product that is in the same category as p. Argument a) On the

About NHibernate's ISession

In this question, the user asks the better way to close sessions because he was having some errors. The most voted answer is Ayende's answer that says: You should always use session.Dispose(); The other are for very strange occurances Should I really always call session.Dispose()? Isn't enough to call session.Close()?

Fluent NHibernate: How do you change the underlying sql type for an automapped collection of strings?

I have a class: public class ParentClass { //other stuff IList<string> ChildPages } When 'IList<string> ChildPages' gets automapped by Fluent NHibernate a 'ChildPages' join table is created with a nvarchar(255) backing field for each string in the collection. But the problem is that I want the sql backing field to be 'text', so that I can have lengthy entries for this entity. What's the easiest way to make this change? How do you change the underlying type of automapp

Nhibernate autopmapping with UseOverridesFromAssemblyOf doesn't call overriding classes of base class

i'm using automapping with fluent nHibernate, very simply, like so: Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString(c => c .Server("(local)\\sql2008") .Database("nHibernate_test") .TrustedConnection())) .Mappings(m => m.AutoMappings.Add( AutoMap.AssemblyOf<Domain.Airport>(cfg) .UseOverridesFromAssemblyOf<ReaderMappingOverride>()

How to export a database using Fluent NHibernate?

How can I export an entire database, with all its tables and data, into a importable file using Fluent NHibernate (or any other preferrable tool)? Edit: To clarify; the exporting should be made programmatically.

Is NHibernate 3.0 built-in Linq provider stable?

Can i depend on NHibernate 3.0 built-in Linq provider to perform complex queries contain aggregate functions such as Max and Min and contains string operations such as Contains, StartsWith, or EndsWith ??

NHibernate - simple join query

A very simple scenario. I have 2 classes: Project and DataStructure. Class Project contains member List<DataStructure>. My goal is to load a Project and all its DataStructures in one call. public class Project { public virtual string Id { get { } set { } } public virtual string Name { get { } set { } } public virtual ISet<DataStructure> DataStructures { get { } set { } } } public class DataStructure { public virtual string Id { get { } set { } } public virtual str

Fluent NHibernate mappings for localization

I am trying to build a Database from NHibernate mappings and have run into a problem. I have many classes with localized string values: public class MyClass1 { public virtual int Id { get; set; } public virtual ShortString Name { get; set; } public virtual LongString Description { get; set; } } public class MyClass2 { public virtual int Id { get; set; } public virtual ShortString Name { get; set; } public virtual LongString Description { get; set; } } and Languages l

Is NHibernate SessionFactory thread safe

According to documentation the SessionFactory should be thread safe: An ISessionFactory is threadsafe, many threads can access it concurrently and request ISessions. I'm looking at the implementation and I can't understand how e.g. OpenSession() can be thread safe: http://nhibernate.svn.sourceforge.net/viewvc/nhibernate/trunk/nhibernate/src/NHibernate/Impl/SessionFactoryImpl.cs?revision=5233&view=markup There are few lock() calls but nothing in OpenSession(). All the lock free thread

Entity Framework and NHibernate - Is caching still a service layer responsibility?

Prior to using ORMs we always performed object caching in our service layer. This gave us the ability to switch between different data layers without having to change our caching implementation. Nowadays we use both Entity Framework (mainly code first) and NHibernate. NHibernate seems to have much better caching features with several 2nd level cache providers available. Another problem I am faced with is that for both of the above ORMs we make use of lazy loaded properties. So if we are retrie

Implementing "where not exists" with NHibernate QueryOver

Using the new QueryOver API in NHibernate, I need to do something equivalent of: select c.* from Category c where not exists ( select * from CategoryProduct cp where cp.CategoryID = c.Id and cp.ProductID = 'DogFood' ) In other words: "Give me all categories that doesn't contain dog food". My initial thought was something like: IEnumerable<Category> FindCategoriesWithoutProduct(Product product) { return _session .QueryOver<Category>() .Where(c

Nhibernate Eagarly loading many-to-many relationship

I have a Category type and an Item type, with a bidirectional many-to-many relationship in-between. Both sides of this relationship are lazy. I want to write a query, either in HQL or ICriteria, that does the following: Given a category's ID, load all its items along with (eagerly loading) those items' Categories collections. What would such a query look like? I got as far as: session.CreateQuery( "from Category c left join fetch c.Items where c.ID = :cid" ) .SetParameter( "cid", of

NHibernate Queryover - How do I return only a child collection

I am running into difficulty with the following nhibernate queryover query. I am probably over-complicating things, but here is the problem: I have an entity named AuctionStatistic that links to an auction (this is uni-directional and I do not have links from auctions back to statistics) I would like to query the statistic table, find all auction IDs and pull back only those that meet a certain threshold - i.e. top 500 auctions by views Once I've gotten the top X (in this example i'm hardcodin

NHibernate multiple column mapping collection

I have this situation: I have several tables table_1, table_2... table_n, they belong to different data but they have some fields in common, record_id, form_id where id is the primary key. All these tables are represented by a single class Record (Id, Form, Attributes) I have another table tbl_attachments which have attachment_id, record_id, form_id (record_id is not enough because the record_id can be repeated over table_X tables. The problem I have is I want to have property Attachments in

Nhibernate Queryover where id is not in list

I have been struggling with this for a while, so I hope some of you QueryOver experts can help. I have a list of blog posts. You can vote on each blog post, and I would like (among other) to recieve a list of posts where the user hasn't voted. First I was thinking about doing something like: Session.QueryOver<BlogPost>() .WhereRestrictionOn(bp => bp.Id) .NotIn(existingBlogPostVotes); (existingBlogPostVoteIds is the ids of the voted blogposts) But this doesn't exist in the QueryOve

CastleWindsor + NHibernate + NCommon IRepository: how to auto-register?

I'm trying to auto-register NHibernate entities as NCommon IRepository's using Castle and I can't figure it out. On a previous project, we used autofac and this is how we accomplished it: autofacContainerBuilder.RegisterGeneric(typeof (NHRepository<>)) .As(typeof (IRepository<>)) .InstancePerLifetimeScope(); Is there an equivalent for Castle? Thanks! EDIT: This is as close as I can get it, but the ComponentActivator fails on instantiating NHRepo

NHibernate composite id mapping issue, bi/uni-directional OneToMany, ManyToOne and ManyToMany

In my project all of entities have composite primary keys [systemId as long, deviceId as long, id as long]. Values filled manualy before I save the entity. I'm using "code first" approach and to provide simplicity references NHibernate.Mapping.Attributes extension to define schema with attributes just like in Java based Hibernate. All entities have an abstract base type which provides shared properties and functionality: [Serializable] public abstract class EntityBase { [CompositeId(0, Na

NHibernate Transaction.Commit automatically closes Session

I have a web application that is using the absolute latest version (3.3) and is using session-by-request session management within a HttpModule, so there are no problems with multiple session conflicts. Unfortunately, I am finding that the session is getting automatically closed immediately after I perform a Transaction.Commit which I only do when I am actually performing a Create, Update or Delete. I am finding this within my NHibernate log. I know for a fact that I am not doing it, because t

Fluent NHibernate Mapping for Table in multiple HasMany Relationships

What is wrong with my class mappings below? public class Foo { public Foo() { ActualCurve = new List<Point>(); TargetCurve = new List<Point>(); } public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual IList<Point> ActualCurve { get; set; } public virtual IList<Point> TargetCurve { get; set; } } public class Point { public virtual int Id { get; set; } public virtual double X { get; s

Where to get latest fluent nhibernate binary

Where to find binary for fluent nhibernate. This page is changed now http://www.fluentnhibernate.org/ and i can't find any binary in it. Is fluent nhibernate still alive and where can i get binary code?

Fluent NHibernate nullable one-to-one mapping

I've been trying to map two objects using a one-to-one bi-directional relationship. The relationship between the two objects is not required. Here are the objects: public class Tenant { public virtual int TenantId { get; set; } public virtual string Name { get; set; } public virtual Unit Unit { get; set; } } public class Unit { public virtual int UnitId { get; set; } public virtual string UnitNumber { get; set; } public virtual int Rooms { get; set; } public vi

how to get records from multiple tables using joins by IQueryOver in nHibernate?

I have three tables: User -> UserId, username UserGroup -> UserGroupId, GroupName UserGroupMember -> UserId, UserGroupId I have created the corresponding mappings using nHibernate, but when I try to search for the groupname and retreive the users list which belongs to the particular group, I am receiving error and not able to retrieve the results. Can someone please help me to resolve this issue.

NHibernate taking longer time executing simple query

I am facing very strange issue re NHibernate and now it is become headache. NHibernate is taking longer time (2-3 minute) than expected time (few milliseconds) to execute such a simple query. The database is Oracle and I am using ODP driver. I have checked all necessary configuration re NHibernate and Spring which looks ok to me. When I execute the same query in sqldeveloper, it is giving result in milliseconds. FYI - When I execute another query which has three inner join with complex model w

NHibernate ConventionModelMapper; What is the difference between IsRootEntity & IsEntity

I'm playing around with Sharp Architecture Lite, which emphasizes convention over configuration, and trying to understand how the NHibernate ConventionModelMapper works. Specifically, I can't tell the difference between the IsRootEntity & IsEntity methods below (BTW, Entity is an abstract class that ships with Sharp Arch): internal static class Conventions { public static void WithConventions(this ConventionModelMapper mapper, Configuration configuration) {

Nhibernate Issue when quering Hierarchy to Hierarchy relationship

A Teacher has a one-to-one with a Student. A SpecialTeacher extends Teacher but deals specifically with SpecialStudents. Using table per class in the hierarchies. public class Teacher { public virtual int Id { get; set; } public virtual int DepartmentId { get; set; } public virtual String Name { get; set; } public virtual Student Student { get; set; } } public class SpecialTeacher : Teacher { public virtual string TelephoneNumber {

Nhibernate How can i create a criteria for This SQL

I Stuck in this query. If any body know the Criteria of NHibernate please help me select * from ViewFabricStock VFS where VFS.REORDER_METER > VFS.VIRTUAL_STOCK VFS.REORDER_METER ,VFS.VIRTUAL_STOCK is a model property i would like also know about this query select * from ViewFabricStock VFS where fabricName like LocalizeFabricName

Nhibernate How to get nested objects using ICriteria Projections

I have data model like this: class Hand { public int id; ... } class Person { public int id; public string name; public IList<Hand> hands; ... } To get data from database, I do this: ICriteria criteria = databaseSession.CreateCriteria(typeof(Person)); ProjectionList projections = Projections.ProjectionList(); projections .Add(Projections.Property("id").As("id")) .Add(Projections.Property("name").As("name")) .Add(Projections.Property("hands").As("ha

Nhibernate QueryOver Get all Parents with less than 3 childs

I am fighting with this query since yesterday morning and cannot find a solution. What I want to do is to have a query like: IList<Parent> = _session.QueryOver<Parent>() .Where(Restrictions.lt(x => x.Childs.Count,4)) .List<Parent>(); Anyone having an idea how to do it? Childs is a HasMany-Collection. Regards, Martin

NHibernate stateless session - what is the data aliasing effect?

The NHibernate documentation for the stateless session interface states, among others: Stateless sessions are vulnerable to data aliasing effects, due to the lack of a first-level cache. I couldn't find an explanation for this. What does 'data aliasing effects' mean? If you could give examples... that'd be great.

Castle Windsor/NHibernate/FactoryMethod and registering an NHIbernate EmptyInterceptor

I am using Castle Windsor for my IoC along with NHIbernate in an ASP.NET MVC app. It works great registered as follows: container.Register(Component.For<ISessionFactoryBuilder.().ImplementedBy<SessionFactoryBuilder>().LifestyleSingleton()); // Register the NHibernate session factory as a singleton using custom SessionFactoryBuilder.BuildSessionFactory method. container.Register(Component.For<ISessionFactory>().UsingFactoryMethod(k => k.Resolve<ISessionFactoryBuilder>().

DB2 Fluent NHibernate mapping duplicate records in HasMany mapping

I accessing a pre-existing database (actually DB2 on an IBM i), and have an issue with the mappings for the following (simple) structure in Fluent NHibernate. I have had to construct an artificial example, so forgive any ommissions. Job ... public class Job { public virtual string JobCode { get; set; } public virtual string Owner{ get; set; } public virtual IList<Deliverable> Deliverables { get; set; } public Job() { Deliverables = new List<Deliverable&g

Nhibernate breeze deep expand with inheritance

I have some troubles with breeze and expanding deep properties. Here's the code: public abstract class BaseEntity { public virtual Guid? Id { get; set; } } public partial class Request : BaseEntity { public virtual IList<ServiceBase> Services { get; set; } public Request() { this.Services = new List<ServiceBase>(); } } public abstract class ServiceBase : BaseEntity { public virtual Guid? RequestId { get; set; } public virtual Request Request { ge

Nhibernate ThreadLocalSessionContext: Current session context does not extend class CurrentSessionContext

When using ThreadLocalSessionContext I get this exception: "Current session context does not extend class CurrentSessionContext." upon call to CurrentSessionContext.HasBind. When switching to CurrentSessionContext<ThreadStaticSessionContext>() in my fluent configuration everything works fine. I am running inside console application with following packages: <packages> <package id="FluentNHibernate" version="" targetFramework="net451" /> <package id="Iesi.Collectio

Updated documentation for Nhibernate?

I'm looking for updated documentation on Nhibernate, particularly with the information regarding the upgrades in Nhibernate 4.0. The official documentation appears to only have information regarding Nhibernate 2.1.0, but according to the wikipedia page for Nhibernate there have been a few substantial changes to Nhibernate, most notably with the fact that you no longer need .hbm.xml files, something that is still a focal point to the original documentation. Any tutorials that are available about

Nhibernate How to get SQL with parameter values on an exception

Hard to believe, but I can't seem to find a straight answer for this: How can I get the SQL statement including the parameter values when the statement generates an exception and only when it generates an exception. I know how to log the statement+parameters for every SQL generated, but that's way too much. When there's a System.Data.SqlClient.SqlException, though, it only provides the SQL, not the parameter values. How can I catch that at a point where I have access to the that data so that

NHibernate TPH, QueryOver and discriminator

I have following class hierarchy mapped to database using Table-Per-Hierarchy class A {}; class B: A {}; class C: A {}; How can I sort data based on discriminator value _session.QueryOver<A>().OrderBy(???) Thanks

  1    2   3   4   5   6  ... 下一页 最后一页 共 34 页