Search Results

Search found 50 results on 2 pages for 'icriteria'.

Page 2/2 | < Previous Page | 1 2 

  • NHibernate query against the key field of a dictionary (map)

    - by Carl Raymond
    I have an object model where a Calendar object has an IDictionary<MembershipUser, Perms> called UserPermissions, where MembershipUser is an object, and Perms is a simple enumeration. This is in the mapping file for Calendar as <map name="UserPermissions" table="CalendarUserPermissions" lazy="true" cascade="all"> <key column="CalendarID"/> <index-many-to-many class="MembershipUser" column="UserGUID" /> <element column="Permissions" type="CalendarPermission" not-null="true" /> </map> Now I want to execute a query to find all calendars for which a given user has some permission defined. The permission is irrelevant; I just want a list of the calendars where a given user is present as a key in the UserPermissions dictionary. I have the username property, not a MembershipUser object. How do I build that using QBC (or HQL)? Here's what I've tried: ISession session = SessionManager.CurrentSession; ICriteria calCrit = session.CreateCriteria<Calendar>(); ICriteria userCrit = calCrit.CreateCriteria("UserPermissions.indices"); userCrit.Add(Expression.Eq("Username", username)); return calCrit.List<Calendar>(); This constructed invalid SQL -- the WHERE clause contained WHERE membership1_.Username = @p0 as expected, but the FROM clause didn't include the MemberhipUsers table. Also, I really had to struggle to learn about the .indices notation. I found it by digging through the NHibernate source code, and saw that there's also .elements and some other dotted notations. Where's a reference to the allowed syntax of an association path? I feel like what's above is very close, and just missing something simple.

    Read the article

  • similarity match

    - by csetzkorn
    Many search engine have the 'did you mean' functionality. Is there a simple way to use (N)Hibernate (e.g. ICriteria) to find an entity (e.g. keyword) based on similarity. Please note that I do not mean Expression.Like or something like this. I hope this question makes sense. Thanks. Christian

    Read the article

  • Why doesn't nHibernate support LIMIT when doing "join fetch"?

    - by HeavyWave
    In nHibernate, if you do an HQL query with "join fetch" to eagerly load a child collection, nHibernate will ignore SetMaxResults and SetFirstResult and try to retrieve every single item from the database. Why? This behavior is specific to HQL, as ICriteria supports eager loading (with an outer join, though) and LIMIT. There are more details here http://www.lesnikowski.com/blog/index.php/nhibernate-ignores-setmaxresults-in-sql/ .

    Read the article

  • NHibernate FetchMode.Lazy

    - by RyanFetz
    I have an object which has a property on it that has then has collections which i would like to not load in a couple situations. 98% of the time i want those collections fetched but in the one instance i do not. Here is the code I have... Why does it not set the fetch mode on the properties collections? [DataContract(Name = "ThemingJob", Namespace = "")] [Serializable] public class ThemingJob : ServiceJob { [DataMember] public virtual Query Query { get; set; } [DataMember] public string Results { get; set; } } [DataContract(Name = "Query", Namespace = "")] [Serializable] public class Query : LookupEntity<Query>, DAC.US.Search.Models.IQueryEntity { [DataMember] public string QueryResult { get; set; } private IList<Asset> _Assets = new List<Asset>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Asset> Assets { get { return _Assets; } set { _Assets = value; } } private IList<Theme> _Themes = new List<Theme>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Theme> Themes { get { return _Themes; } set { _Themes = value; } } private IList<Affinity> _Affinity = new List<Affinity>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Affinity> Affinity { get { return _Affinity; } set { _Affinity = value; } } private IList<Word> _Words = new List<Word>(); [IgnoreDataMember] [System.Xml.Serialization.XmlIgnore] public IList<Word> Words { get { return _Words; } set { _Words = value; } } } using (global::NHibernate.ISession session = NHibernateApplication.GetCurrentSession()) { global::NHibernate.ICriteria criteria = session.CreateCriteria(typeof(ThemingJob)); global::NHibernate.ICriteria countCriteria = session.CreateCriteria(typeof(ThemingJob)); criteria.AddOrder(global::NHibernate.Criterion.Order.Desc("Id")); var qc = criteria.CreateCriteria("Query"); qc.SetFetchMode("Assets", global::NHibernate.FetchMode.Lazy); qc.SetFetchMode("Themes", global::NHibernate.FetchMode.Lazy); qc.SetFetchMode("Affinity", global::NHibernate.FetchMode.Lazy); qc.SetFetchMode("Words", global::NHibernate.FetchMode.Lazy); pageIndex = Convert.ToInt32(pageIndex) - 1; // convert to 0 based paging index criteria.SetMaxResults(pageSize); criteria.SetFirstResult(pageIndex * pageSize); countCriteria.SetProjection(global::NHibernate.Criterion.Projections.RowCount()); int totalRecords = (int)countCriteria.List()[0]; return criteria.List<ThemingJob>().ToPagedList<ThemingJob>(pageIndex, pageSize, totalRecords); }

    Read the article

  • Disctinct from the table

    - by bharat
    ICriteria crit = session.CreateCriteria(); foreach (ICriteriaItem<object> param in filters) { crit.Add(Expression.Eq(param.PropertyName, param.FilterValue)); } crit.SetProjection(Projections.Distinct(Projections.ProjectionList())); -- disctinct not working can you please help me crit.AddOrder(new Order(sortField, sortOrderAscending)); crit.SetFirstResult(pageNumber * pageSize); crit.SetMaxResults(pageSize); transaction.Commit(); return crit.List<IHCOSpendTable>();

    Read the article

  • invoke sql function using nhibernate?

    - by net205
    I want to query like this: select * from table where concat(',', ServiceCodes, ',') like '%,33,%'; select * from table where (','||ServiceCodes||',') like '%,33,%'; so, I wrote this code: ICriteria cri = NHibernateSessionReader.CreateCriteria(typeof(ConfigTemplateList)); cri.Add(Restrictions.Like(Projections.SqlFunction("concat", NHibernateUtil.String, Projections.Property("ServiceCodes")), "%,33,%")); I get sql similar : select * from table where (ServiceCodes) like '%,33,%'; But it is not what I want,how to do it??? thanks!

    Read the article

  • Nhibernate setting query time out period for commands and pessimistic locking

    - by Nagesh
    I wish to specify a specific command timeout (or LOCK_TIMEOUT) for an SQL and once this time out is reached an exception (or alert) has to be raised in nHibernate. The following is an example pseudo-code what I have written: using (var session = sessionFactory.OpenSession()) { using (var sqlTrans = session.BeginTransaction()) { ICriteria criteria = session.CreateCriteria(typeof(Foo)); criteria.SetTimeout(5); //Here is the specified command timout, eg: property SqlCommand.CommandTimeout Foo fooObject = session.Load<Foo>(primaryKeyIntegerValue, LockMode.Force); session.SaveOrUpdate(fooObject); sqlTrans.Commit(); } } In SQL server we used to achieve this using the following SQL: BEGIN TRAN SET LOCK_TIMEOUT 500 SELECT * FROM Foo WITH (UPDLOCK, ROWLOCK) WHERE PrimaryKeyID = 1000001 If PrimaryKeyID row would have locked in other transaction the following error message is being shown by SQL Server: Msg 1222, Level 16, State 51, Line 3 Lock request time out period exceeded Similarly I wish to show a lock time out or command time out information using nHibernate. Please help me to achieve this. Thanks in advance for your help.

    Read the article

  • NHibernate filters don't work with Session.Get

    - by Khash
    I'm trying to implement a Soft-deletable repository. Usually this can be easily done with a Delete Event listener. To filter out the deleted entities, I can add a Where attribute to my class mapping. However, I also need to implement two more methods in the repository for this entity: Restore and Purge. Restore will "undelete" entities and Purge will hard-delete them. This means I can't use Where attribute (since it block out soft-deleted entities to any access) I tried using filters instead. I can create a filter and enable or disable it within session to achieve the same result. But the problem is filters don't have any effect on Session.Get method (they only affect ICriteria based access). Any ideas as to how solve this problem? Thanks

    Read the article

  • Nhibernate Left Outer Join Return First Record of the Join

    - by Touch
    I have the following mappings of which Im trying to bring back 0 - 1 Media Id associated with a Product using a left join (I havnt included my attempt as it confuses the situation) ICriteria productCriteria = Session.CreateCriteria(typeof(Product)); productCriteria .CreateAlias("ProductCategories", "pc", JoinType.InnerJoin) .CreateAlias("pc.ParentCategory", "category") .CreateAlias("category.ParentCategory", "group") .Add(Restrictions.Eq("group.Id", 333)) .SetProjection( Projections.Distinct( Projections.ProjectionList() .Add(Projections.Alias(Projections.Property("Id"), "Id")) .Add(Projections.Alias(Projections.Property("Title"), "Title")) .Add(Projections.Alias(Projections.Property("Price"), "Price")) .Add(Projections.Alias(Projections.Property("media.Id"), "SearchResultMediaId")) // I NEED THIS ) ) .SetResultTransformer(Transformers.AliasToBean<Product>()); IList<Product> products = productCriteria .SetFirstResult(0) .SetMaxResults(10) .List<Product>(); I need the query to populate the SearchResultMediaId with Media.Id, I only want to bring back the first Media in a left outer join, as this is 1 to many association between Product and Media Product is mapped to Media in the following way mapping.HasManyToMany<Media>(x => x.Medias) .Table("ProductMedias") .ParentKeyColumn("ProductId") .ChildKeyColumn("MediaId") .Cascade.AllDeleteOrphan() .LazyLoad() .AsBag(); Any Help would be fantastic.

    Read the article

  • NHibernate: how to do lookup a specific date

    - by Daoming Yang
    How I can lookup a specific date in Nhibernate? I'm currently using this to lookup one day's order. ICriteria criteria = SessionManager.CurrentSession.CreateCriteria(typeof(Order)) .Add(Expression.Between("DateCreated", date.Date.AddDays(-1), date.Date.AddDays(1))) .AddOrder(NHibernate.Criterion.Order.Desc("OrderID")); I tried the following code, but they did bring the data for me. Expression.Eq("DateCreated", date) Expression.Like("DateCreated", date) Note: The pass in date value will be like this 2010-04-03 00:00:00, The actual date value in the database will be like this 2010-03-13 11:17:16.000 Can anyone let me know how to do this? Many thanks.

    Read the article

  • NHibernate: how to do lookup a specific date in Nhibernate

    - by Daoming Yang
    How I can lookup a specific date in Nhibernate? I'm currently using this to lookup one day's order. ICriteria criteria = SessionManager.CurrentSession.CreateCriteria(typeof(Order)) .Add(Expression.Between("DateCreated", date.Date.AddDays(-1), date.Date.AddDays(1))) .AddOrder(NHibernate.Criterion.Order.Desc("OrderID")); I tried the following code, but they did bring the data for me. Expression.Eq("DateCreated", date) Expression.Like("DateCreated", date) Note: The pass in date value will be like this 2010-04-03 00:00:00, The actual date value in the database will be like this 2010-03-13 11:17:16.000 Can anyone let me know how to do this? Many thanks.

    Read the article

  • Need help optimizing a NHibernate criteria query that uses Restrictions.In(..)

    - by Chris F
    I'm trying to figure out if there's a way I can do the following strictly using Criteria and DetachedCriteria via a subquery or some other way that is more optimal. NameGuidDto is nothing more than a lightweight object that has string and Guid properties. public IList<NameGuidDto> GetByManager(Employee manager) { // First, grab all of the Customers where the employee is a backup manager. // Access customers that are primarily managed via manager.ManagedCustomers. // I need this list to pass to Restrictions.In(..) below, but can I do it better? Guid[] customerIds = new Guid[manager.BackedCustomers.Count]; int count = 0; foreach (Customer customer in manager.BackedCustomers) { customerIds[count++] = customer.Id; } ICriteria criteria = Session.CreateCriteria(typeof(Customer)) .Add(Restrictions.Disjunction() .Add(Restrictions.Eq("Manager", manager)) .Add(Restrictions.In("Id", customerIds))) .SetProjection(Projections.ProjectionList() .Add(Projections.Property("Name"), "Name") .Add(Projections.Property("Id"), "Guid")) // Transform results to NameGuidDto criteria.SetResultTransformer(Transformers.AliasToBean(typeof(NameGuidDto))); return criteria.List<NameGuidDto>(); }

    Read the article

  • Nhibernate and not-exists query

    - by Dan
    I'm trying to construct a query in NHibernate to return a list of customers with no orders matching a specific criteria. My Customer object contains a set of Orders: <set name="Orders"> <key column="CustomerID" /> <one-to-many class="Order" /> </set> How do I contruct a query using NHibernate's ICriteria API to get a list of all customers who have no orders? Using native SQL, I am able to represent the query like this: select * from tblCustomers c where not exists (select 1 from tblOrders o where c.ID = o.CustomerID) I have been unable to figure out how to do this using aliases and DetatchedCriteria objects. Any guidance would be appreciated! Thanks!

    Read the article

  • NHibernate. Distinct parent child fetching

    - by Andrew Kalashnikov
    Hello. I've got common NH mapping; <class name="Order, SummaryOrder.Core" table='order'> <id name="Id" unsaved-value="0" type="int"> <column name="id" not-null="true"/> <generator class="native"/> </id> <many-to-one name="Client" class="SummaryOrderClient, SummaryOrder.Core" column="summary_order_client_id" cascade="none"/> <many-to-one name="Provider" class="SummaryOrderClient, SummaryOrder.Core" column="summary_order_provider_id" cascade="none"/> <set name="Items" cascade="all"> <key column="order_id"/> <one-to-many class="OrderItem, Clients.Core" /> </set> </class> Want get list by this criteria ICriteria criteria = NHibernateStateLessSession.CreateCriteria(typeof(SummaryOrder.Core.Domains.Order)); ; criteria.Add(Restrictions.Or (Restrictions.Eq(String.Format("{0}.Id", SummaryOrder.Core.Domains.Order.Properties.Client), idClient), Restrictions.Eq(String.Format("{0}.Id", SummaryOrder.Core.Domains.Order.Properties.Provider), idClient))). SetResultTransformer(new DistinctRootEntityResultTransformer()). SetFetchMode(SummaryOrder.Core.Domains.Order.Properties.Items, FetchMode.Join); return criteria.List<SummaryOrder.Core.Domains.Order>() as List<SummaryOrder.Core.Domains.Order> But I've got duplicates.. When I execute One restriction (without OR) I got distinct collection of orders, but Restriction OR brakes my query. I wanna get distinct(at client yet) collection of orders. What's wrong. Please HELP!

    Read the article

  • Is it possible to unit test methods that rely on NHibernate Detached Criteria?

    - by Aim Kai
    I have tried to use Moq to unit test a method on a repository that uses the DetachedCriteria class. But I come up against a problem whereby I cannot actually mock the internal Criteria object that is built inside. Is there any way to mock detached criteria? Test Method [Test] [Category("UnitTest")] public void FindByNameSuccessTest() { //Mock hibernate here var sessionMock = new Mock<ISession>(); var sessionManager = new Mock<ISessionManager>(); var queryMock = new Mock<IQuery>(); var criteria = new Mock<ICriteria>(); var sessionIMock = new Mock<NHibernate.Engine.ISessionImplementor>(); var expectedRestriction = new Restriction {Id = 1, Name="Test"}; //Set up expected returns sessionManager.Setup(m => m.OpenSession()).Returns(sessionMock.Object); sessionMock.Setup(x => x.GetSessionImplementation()).Returns(sessionIMock.Object); queryMock.Setup(x => x.UniqueResult<SopRestriction>()).Returns(expectedRestriction); criteria.Setup(x => x.UniqueResult()).Returns(expectedRestriction); //Build repository var rep = new TestRepository(sessionManager.Object); //Call repostitory here to get list var returnR = rep.FindByName("Test"); Assert.That(returnR.Id == expectedRestriction.Id); } Repository Class public class TestRepository { protected readonly ISessionManager SessionManager; public virtual ISession Session { get { return SessionManager.OpenSession(); } } public TestRepository(ISessionManager sessionManager) { } public SopRestriction FindByName(string name) { var criteria = DetachedCriteria.For<Restriction>().Add<Restriction>(x => x.Name == name) return criteria.GetExecutableCriteria(Session).UniqueResult<T>(); } } Note I am using "NHibernate.LambdaExtensions" and "Castle.Facilities.NHibernateIntegration" here as well. Any help would be gratefully appreciated.

    Read the article

  • NHibernate complex order query

    - by manu08
    Here's my simplified domain public class Notification { public Guid ID { get; set; } public string Name { get; set; } public IEnumerable<Location> Locations { get; set; } } public class Location { public Guid Id { get; set; } public string Name { get; set; } public decimal Longitude { get; set; } public decimal Latitude { get; set; } } Notifications and Locations have a many-to-many relationship (defined in table LocationsOnNotification). What I'd like to do is query for the nearest 10 Notifications from a given longitude and latitude. I've been trying to use ICriteria, but I'm not sure how to specify the ordering correctly: return Session.CreateCriteria<Notification>() .SetFirstResult(firstIndex) .SetMaxResults(maxResults) .AddOrder(Order.Asc( WHAT GOES HERE! )) .List<Notification>(); What I've been thinking of so far is adding a formula property to the Location mapping; something like this: <property name='Distance' formula='lots of geometry'/> But I'm not sure if that can take in parameters (since I'd need to pass in the user's location to calculate the distance), plus I'm not sure how to specify it in the Order.Asc clause given that it's a property on a many-to-many association class. Any ideas? Or perhaps I should take a different approach altogether. Thanks in advance!

    Read the article

  • Nhibernate - stuck with detached criteria (asp.net mvc 1 with nhibernate 2) c#

    - by Jen
    OK so I can't find a good example of this so I can better understand how to use detached criteria (assuming that's what I want to use in the first place). I have 2 tables. Placement and PlacementSupervisor My PlacementSupervisor table has a FK of PlacementID which relates to Placement.PlacementID - though my nhibernate model class has PlacementSupervisor . Placement (rather than specifically specifying a property of placement ID - not sure if this is important). What I am trying to do is - if values are passed through for the supervisor ID I want to restrict placements with that supervisor id. Have tried: ICriteria query = m_PlacementRepository.QueryAlias("p") .... if (criteria.SupervisorId > 0 && !string.IsNullOrEmpty(criteria.SupervisorTypeId)) { DetachedCriteria entityQuery = DetachedCriteria.For<PlacementSupervisor>("sup") .Add(Restrictions.And( Restrictions.Eq("sup.supervisorId", criteria.SupervisorId), Restrictions.Eq("sup.supervisorTypeId", criteria.SupervisorTypeId) )) .SetProjection(Projections.ProjectionList() .AddPropertyAlias("Placement.PlacementId", "PlacementId") ); query.Add(Subqueries.PropertyIn("p.PlacementId", entityQuery)); } Which just gives me the error: Could not find a matching criteria info provider to: (sup.supervisorId = 5 and sup.supervisorTypeId = U) Firstly supervisorTypeId is a string. Secondly I don't understand how to achieve what I'm trying to do so have just been trying various combinations of projections, and property aliases and subquery options..as I don't get how I'm supposed to join to another table/entity when the FK key sits in the second table. Can someone point me in the right direction. It seems like such an easy thing to do from a data perspective that hopefully I'm just missing something obvious!!

    Read the article

  • NHibernate Criteria Find by Id

    - by user315648
    Hello, I have 2 entities: public class Authority : Entity { [NotNull, NotEmpty] public virtual string Name { get; set; } [NotNull] public virtual AuthorityType Type { get; set; } } public class AuthorityType : Entity { [NotNull, NotEmpty] public virtual string Name { get; set; } public virtual string Description { get; set; } } Now I wish to find all authorities from repository by type. I tried doing it like this: public IList<Authority> GetAuthoritiesByType(int id) { ICriteria criteria = Session.CreateCriteria(typeof (Authority)); criteria.Add(Restrictions.Eq("Type.Id", id)); IList<Authority> authorities = criteria.List<Authority>(); return authorities; } However, I'm getting an error that something is wrong with the SQL ("could not execute query". The innerexception is following: {"Invalid column name 'TypeFk'.\r\nInvalid column name 'TypeFk'."} Any advice ? Any other approach ? Best wishes, Andrew

    Read the article

  • NHibernate: Using value tables for optimization AND dynamic join

    - by Kostya
    Hi all, My situation is next: there are to entities with many-to-many relation, f.e. Products and Categories. Also, categories has hierachial structure, like a tree. There is need to select all products that depends to some concrete category with all its childs (branch). So, I use following sql statement to do that: SELECT * FROM Products p WHERE p.ID IN ( SELECT DISTINCT pc.ProductID FROM ProductsCategories pc INNER JOIN Categories c ON c.ID = pc.CategoryID WHERE c.TLeft >= 1 AND c.TRight <= 33378 ) But with big set of data this query executes very long and I found some solution to optimize it, look at here: DECLARE @CatProducts TABLE ( ProductID int NOT NULL ) INSERT INTO @CatProducts SELECT DISTINCT pc.ProductID FROM ProductsCategories pc INNER JOIN Categories c ON c.ID = pc.CategoryID WHERE c.TLeft >= 1 AND c.TRight <= 33378 SELECT * FROM Products p INNER JOIN @CatProducts cp ON cp.ProductID = p.ID This query executes very fast but I don't know how to do that with NHIbernate. Note, that I need use only ICriteria because of dynamic filtering\ordering. If some one knows a solution for that, it will be fantastic. But I'll pleasure to any suggestions of course. Thank you ahead, Kostya

    Read the article

  • Inheritance - Could not initialize proxy - no Session.

    - by Ninu
    hello....i'm newbie developer.... i really need help at now... i just get started with Nhibernate thing at .Net... when i learn Inheritance and try it...it makes me confusing...why i get error like this : Initializing[AP.Core.Domain.AccountPayable.APInvoice#API03/04/2010/001]-Could not initialize proxy - no Session. this is my xml : <class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="AP.Core.Domain.AccountPayable.APAdjustment, AP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="APAdjustment"> <id name="AdjustmentNumber" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="AdjustmentNumber" length="17" /> <generator class="assigned" /> </id> <property name="Amount" type="System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Amount" /> </property> <property name="TransactionDate" type="System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="TransactionDate" /> </property> <many-to-one class="AP.Core.Domain.AccountPayable.APInvoice, AP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" lazy="proxy" name="PurchaseInvoice"> <column name="PurchaseInvoice_id" not-null="true" /> </many-to-one> <joined-subclass name="AP.Core.Domain.AccountPayable.APCreditAdjustment, AP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" lazy="true" table="APCreditAdjustment"> <key> <column name="APAdjustment_id" /> </key> </joined-subclass> </class> </hibernate-mapping> and this is inheritance Class : Parent Class -- public class APAdjustment { #region :FIELD private string adjustmentNumber; private decimal amount; private DateTime transactionDate; private APInvoice purchaseInvoice; Child Class -- public class APCreditAdjustment : APAdjustment { public APCreditAdjustment(){ and this my Data access : public IList<APAdjustment> GetByNameAll() { ICriteria criteria = Nhibernatesession.CreateCriteria(typeof(APAdjustment)); return criteria.List<APAdjustment>() ; } My Problem is : when i load data with gridview ...it works...but i change the property to autogenerate="true" ...i missing "PurchaseInvoice" field...and i change to bind manually,and it works..when i edit that gridview ...i get this error... Initializing[AP.Core.Domain.AccountPayable.APInvoice#API03/04/2010/001]-Could not initialize proxy - no Session so then i change my xml ...lazy="no-proxy" ...it still work...but when edit again ...i get error again ..and i do "Comment out the selected lines" to my association "Many-to-one"...i really works it..but that's not i want... CAN ANYBODY HELP ME...??Plizz...:( Note : I almost forget it ,i use fluent hibernate to generate to database.From fluent Hibernate ..i put *.xml file ...so i'm work to xml NHibernate...not fluent hibernate thing...:)

    Read the article

  • How to order a HasMany collection by a child property with Fluent NHibernate mapping

    - by Geoff Hardy
    I am using Fluent NHibernate to map the following classes: public abstract class DomainObject { public virtual int Id { get; protected internal set; } } public class Attribute { public virtual string Name { get; set; } } public class AttributeRule { public virtual Attribute Attribute { get; set; } public virtual Station Station { get; set; } public virtual RuleTypeId RuleTypeId { get; set; } } public class Station : DomainObject { public virtual IList<AttributeRule> AttributeRules { get; set; } public Station() { AttributeRules = new List<AttributeRule>(); } } My Fluent NHibernate mappings look like this: public class AttributeMap : ClassMap<Attribute> { public AttributeMap() { Id(o => o.Id); Map(o => o.Name); } } public class AttributeRuleMap : ClassMap<AttributeRule> { public AttributeRuleMap() { Id(o => o.Id); Map(o => o.RuleTypeId); References(o => o.Attribute).Fetch.Join(); References(o => o.Station); } } public class StationMap : ClassMap<Station> { public StationMap() { Id(o => o.Id); HasMany(o => o.AttributeRules).Inverse(); } } I would like to order the AttributeRules list on Station by the Attribute.Name property, but doing the following does not work: HasMany(o => o.AttributeRules).Inverse().OrderBy("Attribute.Name"); I have not found a way to do this yet in the mappings. I could create a IQuery or ICriteria to do this for me, but ideally I would just like to have the AttributeRules list sorted when I ask for it. Any advice on how to do this mapping?

    Read the article

  • How to do a proper search with nhibernate

    - by Denis Rosca
    Hello everyone, i'm working on a small project that is supposed to allow basic searches of the database. Currently i'm using nhibernate for the database interaction. In the database i have 2 tables: Person and Address. The Person table has a many-to-one relationship with Address. The code i've come up with for doing searches is: public IList<T> GetByParameterList(List<QueryParameter> parameterList) { if (parameterList == null) { return GetAll(); } using (ISession session = NHibernateHelper.OpenSession()) { ICriteria criteria = session.CreateCriteria<T>(); foreach (QueryParameter param in parameterList) { switch (param.Constraint) { case ConstraintType.Less: criteria.Add(Expression.Lt(param.ParameterName, param.ParameterValue)); break; case ConstraintType.More: criteria.Add(Expression.Gt(param.ParameterName, param.ParameterValue)); break; case ConstraintType.LessOrEqual: criteria.Add(Expression.Le(param.ParameterName, param.ParameterValue)); break; case ConstraintType.EqualOrMore: criteria.Add(Expression.Ge(param.ParameterName, param.ParameterValue)); break; case ConstraintType.Equals: criteria.Add(Expression.Eq(param.ParameterName, param.ParameterValue)); break; case ConstraintType.Like: criteria.Add(Expression.Like(param.ParameterName, param.ParameterValue)); break; } } try { IList<T> result = criteria.List<T>(); return result; } catch { //TODO: Implement some exception handling throw; } } } The query parameter is a helper object that i use to create criterias and send it to the dal, it looks like this: public class QueryParameter { public QueryParameter(string ParameterName, Object ParameterValue, ConstraintType constraintType) { this.ParameterName = ParameterName; this.ParameterValue = ParameterValue; this.Constraint = constraintType; } public string ParameterName { get; set; } public Object ParameterValue { get; set; } public ConstraintType Constraint { get; set; } } Now this works well if i'm doing a search like FirstName = "John" , but not when i try to give a parameter like Street = "Some Street". It seems that nhibernate is looking for a street column in the Person table but not in the Address table. Any idea on how should i change my code for so i could do a proper search? Tips? Maybe some alternatives? Disclaimer: i'm kind of a noob so please be gentle ;) Thanks, Denis.

    Read the article

  • NHibernate: Collection was modified; enumeration operation may not execute

    - by Daoming Yang
    Hi All, I'm currently struggling with this "Collection was modified; enumeration operation may not execute" issue. I have searched about this error message, and it's all related to the foreach statement. I do have the some foreach statements, but they are just simply representing the data. I did not using any remove or add inside the foreach statement. NOTE: The error randomly happens (about 4-5 times a day). The application is the MVC website. There are about 5 users operate this applications (about 150 orders a day). Could it be some another users modified the collection, and then occur this error? I have log4net setup and the settings can be found here Make sure that the controller has a parameterless public constructor I do have parameterless public constructor in AdminProductController Does anyone know why this happen and how to resolve this issue? A friend (Oskar) mentioned that "Theory: Maybe the problem is that your configuration and session factory is initialized on the first request after application restart. If a second request comes in before the first request is finished, maybe it will also try to initialize and then triggering this problem somehow." Many thanks. Daoming Here is the error message: System.InvalidOperationException Collection was modified; enumeration operation may not execute. System.InvalidOperationException: An error occurred when trying to create a controller of type 'WebController.Controllers.Admin.AdminProductController'. Make sure that the controller has a parameterless public constructor. --- System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --- NHibernate.MappingException: Could not configure datastore from input stream DomainModel.Entities.Mappings.OrderProductVariant.hbm.xml --- System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext() at System.Xml.Schema.XmlSchemaSet.AddSchemaToSet(XmlSchema schema) at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlSchema schema) at System.Xml.Schema.XmlSchemaSet.Add(XmlSchema schema) at NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name) at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name) --- End of inner exception stack trace --- at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception) at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name) at NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly) at NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly) at DomainModel.RepositoryBase..ctor() at WebController.Controllers._baseController..ctor() at WebController.Controllers.Admin.AdminProductController..ctor() at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) --- End of inner exception stack trace --- at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) --- End of inner exception stack trace --- at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) UPDATE CODE: In my Global.asax.cs, I'm doing this: protected void Application_BeginRequest(object sender, EventArgs e) { ManagedWebSessionContext.Bind(HttpContext.Current, SessionManager.SessionFactory.OpenSession()); } protected void Application_EndRequest(object sender, EventArgs e) { ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionManager.SessionFactory); if (session != null) { try { if (session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } else { session.Flush(); } } finally { session.Close(); } } } In the SessionManager class, I'm doing: public class SessionManager { private readonly ISessionFactory sessionFactory; public static ISessionFactory SessionFactory { get { return Instance.sessionFactory; } } private ISessionFactory GetSessionFactory() { return sessionFactory; } public static SessionManager Instance { get { return NestedSessionManager.sessionManager; } } public static ISession OpenSession() { return Instance.GetSessionFactory().OpenSession(); } public static ISession CurrentSession { get { return Instance.GetSessionFactory().GetCurrentSession(); } } private SessionManager() { Configuration config = new Configuration().Configure(); config.AddAssembly(Assembly.GetExecutingAssembly()); sessionFactory = config.BuildSessionFactory(); } class NestedSessionManager { internal static readonly SessionManager sessionManager = new SessionManager(); } } In the Repository, I'm doing this: public IEnumerable<User> GetAll() { ICriteria criteria = SessionManager.CurrentSession.CreateCriteria(typeof(User)); return criteria.List<User>(); } In the Controller, I'm doing this: public class UserController : _baseController { IUserRoleRepository _userRoleRepository; internal static readonly ILogger log = LogManager.GetLogger(typeof(UserController)); public UserController() { _userRoleRepository = new UserRoleRepository(); } public ActionResult UserList() { var myList = _usersRepository.GetAll(); return View(myList); } }

    Read the article

  • NHibernate, could not load an entity when column exists in the database.

    - by Eitan
    This is probably a simple question to answer but I just can't figure it out. I have a "Company" class with a many-to-one to "Address" which has a many to one to a composite id in "City". When I load a "Company" it loads the "Address", but if I call any property of "Address" I get the error: {"could not load an entity: [IDI.Domain.Entities.Address#2213][SQL: SELECT address0_.AddressId as AddressId13_0_, address0_.Street as Street13_0_, address0_.floor as floor13_0_, address0_.room as room13_0_, address0_.postalcode as postalcode13_0_, address0_.CountryCode as CountryC6_13_0_, address0_.CityName as CityName13_0_ FROM Address address0_ WHERE address0_.AddressId=?]"} The inner exception is: {"Invalid column name 'CountryCode'.\r\nInvalid column name 'CityName'."} What I don't understand is that I can run the query in sql server 2005 and it works, furthermore both those columns exist in the address table. Here are my HBMs: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="IDI.Domain" namespace="IDI.Domain.Entities" > <class name="IDI.Domain.Entities.Company,IDI.Domain" table="Companies"> <id column="CompanyId" name="CompanyId" unsaved-value="0"> <generator class="native"></generator> </id> <property column="Name" name="Name" not-null="true" type="String"></property> <property column="NameEng" name="NameEng" not-null="false" type="String"></property> <property column="Description" name="Description" not-null="false" type="String"></property> <property column="DescriptionEng" name="DescriptionEng" not-null="false" type="String"></property> <many-to-one name="Address" column="AddressId" not-null="false" cascade="save-update" class="IDI.Domain.Entities.Address,IDI.Domain"></many-to-one> <property column="Telephone" name="Telephone" not-null="false" type="String"></property> <property column="TelephoneTwo" name="TelephoneTwo" not-null="false" type="String"></property> <property column="Fax" name="Fax" not-null="false" type="String"></property> <property column="ContactMan" name="ContactMan" not-null="false" type="String"></property> <property column="ContactManEng" name="ContactManEng" not-null="false" type="String"></property> <property column="Email" name="Email" not-null="false" type="String"></property> </class> </hibernate-mapping> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="IDI.Domain" namespace="IDI.Domain.Entities" > <class name="IDI.Domain.Entities.Address,IDI.Domain" table="Address"> <id name="AddressId" column="AddressId" type="Int32"> <generator class="native"></generator> </id> <property name="Street" column="Street" not-null="false" type="String"></property> <property name="Floor" column="floor" not-null="false" type="Int32"></property> <property name="Room" column="room" not-null="false" type="Int32"></property> <property name="PostalCode" column="postalcode" not-null="false" type="string"></property> <many-to-one class="IDI.Domain.Entities.City,IDI.Domain" name="City" update="false" insert="false"> <column name="CountryCode" sql-type="String" ></column> <column name="CityName" sql-type="String"></column> </many-to-one> </class> </hibernate-mapping> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="IDI.Domain" namespace="IDI.Domain.Entities" > <class name="IDI.Domain.Entities.City,IDI.Domain" table="Cities"> <composite-id> <key-many-to-one class="IDI.Domain.Entities.Country,IDI.Domain" name="CountryCode" column="CountryCode"> </key-many-to-one> <key-property name="Name" column="Name" type="string"></key-property> </composite-id> </class> </hibernate-mapping> Here is my code that calls the Company: IList<BursaUser> user; if(String.IsNullOrEmpty(email) && String.IsNullOrEmpty(company)) return null; ICriteria criteria = Session.CreateCriteria(typeof (BursaUser), "user").CreateCriteria("Company", "comp"); if(String.IsNullOrEmpty(email) || String.IsNullOrEmpty(company) ) { user = String.IsNullOrEmpty(email) ? criteria.Add(Expression.Eq("comp.Name", company)).List<BursaUser>() : criteria.Add(Expression.Eq("user.Email", email)).List<BursaUser>(); } And finally here is where i get the error: "user" was already initialized with the code above: if (user.Company.Address.City == null) user.Company.Address.City = new City(); Thanks.

    Read the article

< Previous Page | 1 2