nhibernate,fluent-nhibernate , setting self as createby


setting self as createby

Question:

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()
    {
        Id(x=>x.Id);
        Map(x=>x.Usernam);
        References(x=>x.CreateBy)
            .Cascade.All()
            .Not.LazyLoad();
     }
}

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


Answer:
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)
           return;
       state[index] = value;
   }
}

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

Related:


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

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

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

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

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

adding initial rows into tables using Fluent migrator


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

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

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

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

Fluent NHibernate mapping via middle table


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

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


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

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

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

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

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

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

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

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


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

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

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

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

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 - exception occurred during configuration


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

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

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

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

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

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

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

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

Fluent nHibernate - how to select DISTINCT dates without time?


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

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

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

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

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