nhibernate,fluent-nhibernate , setting self as createby

setting self as createby


Tag: 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
    int Id;
    string Username;
    User CreateBy;

public class UserMap : ClassMap<User>
    public UserMap()

If the db field 'CreateBy' is set to not null, how do we set the CreateBy to the user who is trying to register?

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 userId = [Your-current-user].Current().UserId; 
       Set(@event.Persister, @event.State, "CreatedBy", userId); 
       audit.CreatedBy= userId;    
       return false;

   private void Set(IEntityPersister persister, object[] state, string propertyName, object value)
       var index = Array.IndexOf(persister.PropertyNames, propertyName);
       if (index == -1)
       state[index] = value;

.ExposeConfiguration(cfg => cfg.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new Convention.AuditEventListener() })


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

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

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

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

adding initial rows into tables using Fluent migrator

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

Fluent NHibernate mapping via middle table

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

NHibernate QueryOver CASE WHEN calculate on column value

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

using QueryOver's query seperated

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

Mapping to Date part of Sql DateTime

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

NHibernate Filtered Child Collection Lazy Loaded even with eager fetch specified

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

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

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

Unable to create one-to-one relationship between entities

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

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

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

How to use Log4net to log in File in Windows Application

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

Sort by count 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...

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

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

setting self as createby

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

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

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

Conflicted with the REFERENCE constraint. How to solve this?

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

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

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

NHibernate fluent mapping to an entity property

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 exception: base {NHibernate.HibernateException} = {“illegal access to loading collection”}

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

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

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 - using CreateMultiQuery

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

Fluent nHibernate - how to select DISTINCT dates without time?

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

NHibernate variable limits with SQL 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()...

Fluent NHibernate - exception occurred during configuration

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

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

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=, Culture=neutral, PublicKeyToken=5c61376b85e43767], resource [Eiq.Middleware.Data.DomainRepository.Persistence.xml] line 15' : Could not resolve placeholder 'TDM.providerName'. at...

Select from Table Valued Function nhibernate

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

Outer right join doesn't work in NHibernate

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

Not persister M:N with association class in NHibernate?

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 QueryOver Project enum description to string

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

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

NHibernate SchemaExport.Execute does not create table

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

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

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

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

Trouble combining Linq Expressions into a Func

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 map one-to-many relationship with intermediate table

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

NHibernate query performance with a large number of disjunctions and conjunctions

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

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

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

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