Search Results

Search found 4565 results on 183 pages for 'nhibernate mapping'.

Page 25/183 | < Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >

  • In NHibernate, how do I combine two DetachedCriteria instances

    - by Trevor
    My scenario is this: I have a base NHibernate query to run of the form (I've coded it using DetachedCriteria , but describe it here using SQL syntax): SELECT * FROM Items I INNER JOIN SubItems S on S.FK = I.Key The user interface to show the results of this join allows the user to specify additional criteria: Say: I.SomeField = 'UserValue'. Now, I need the final load command to be: SELECT * FROM Items I INNER JOIN SubItems S on S.FK = I.Key WHERE I.SomeField = 'UserValue' My problem is: I've created a DetachedCriteria with the 'static' aspect of the query (the top join) and the UI creates a DetachedCriteria with the 'dynamic' component of the query. I need to combine the two into a final query that I can execute on the NHibernate session. DefaultCriteria.Add() takes an ICriterion (which are created using the Expression class, and maybe other classes I don't know of which could be the solution to my problem). Does anyone know how I might do what I want?

    Read the article

  • NHibernate WCF Rest IIS7 Fails with Security Exception

    - by RyanFetz
    Here is the error: System.TypeInitializationException: The type initializer for 'NHibernate.Cfg.Environment' threw an exception. --- System.Security.SecurityException: Request for ConfigurationPermission failed while attempting to access configuration section 'hibernate-configuration'. To allow all callers to access the data for this section, set section attribute 'requirePermission' equal 'false' in the configuration file where this section is declared. --- System.Security.SecurityException: Request for the permission of type 'System.Configuration.ConfigurationPermission, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' failed. at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.Configuration.BaseConfigurationRecord.CheckPermissionAllowed(String configKey, Boolean requirePermission, Boolean isTrustedWithoutAptca) We have the trust level set to Full. Note also that we also have a web site that runs the SAME Nhibernate code and has NO issues. Only the WCF REst Web Service Application has this error? Any Thoughts as to WHY this is a problem?

    Read the article

  • NHibernate: Subqueries.Exists not working

    - by cbp
    I am trying to get sql like the following using NHibernate's criteria api: SELECT * FROM Foo WHERE EXISTS (SELECT 1 FROM Bar WHERE Bar.FooId = Foo.Id AND EXISTS (SELECT 1 FROM Baz WHERE Baz.BarId = Bar.Id) So basically, Foos have many Bars and Bars have many Bazes. I want to get all Foos that have Bars with Bazes. To do this, a detached criteria seems best, like this: var subquery = DetachedCriteria.For<Bar>("bar") .SetProjection(Projections.Property("bar.Id")) .Add(Restrictions.Eq("bar.FooId","foo.Id")) // I have also tried replacing "bar.FooId" with "bar.Foo.Id" .Add(Restrictions.IsNotEmpty("bar.Bazes")); return Session.CreateCriteria<Foo>("foo") .Add(Subqueries.Exists(subquery)) .List<Foo>(); However this throws the exception: System.ArgumentException: Could not find a matching criteria info provider to: bar.FooId = foo.Id and bar.Bazes is not empty Is this a bug with NHibernate? Is there a better way to do this?

    Read the article

  • Nhibernate one-to-many with table per subclass

    - by Wayne
    I am customizing N2CMS's database structure, and met with an issue. The two classes are listed below. public class Customer : ContentItem { public IList<License> Licenses { get; set; } } public class License : ContentItem { public Customer Customer { get; set; } } The nhibernate mapping are as follows. <class name="N2.ContentItem,N2" table="n2item"> <cache usage="read-write" /> <id name="ID" column="ID" type="Int32" unsaved-value="0" access="property"> <generator class="native" /> </id> <discriminator column="Type" type="String" /> </class> <subclass name="My.Customer,My" extends="N2.ContentItem,N2" discriminator-value="Customer"> <join table="Customer"> <key column="ItemID" /> <bag name="Licenses" generic="true" inverse="true"> <key column="CustomerID" /> <one-to-many class="My.License,My"/> </bag> </join> </subclass> <subclass name="My.License,My" extends="N2.ContentItem,N2" discriminator-value="License"> <join table="License" fetch="select"> <key column="ItemID" /> <many-to-one name="Customer" column="CustomerID" class="My.Customer,My" not-null="false" /> </join> </subclass> Then, when get an instance of Customer, the customer.Licenses is always empty, but actually there are licenses in the database for the customer. When I check the nhibernate log file, I find that the SQL query is like: SELECT licenses0_.CustomerID as CustomerID1_, licenses0_.ID as ID1_, licenses0_.ID as ID2_0_, licenses0_1_.CustomerID as CustomerID7_0_, FROM n2item licenses0_ inner join License licenses0_1_ on licenses0_.ID = licenses0_1_.ItemID WHERE licenses0_.CustomerID = 12 /* @p0 */ It seems that nhibernate believes that the CustomerID is in the 'n2item' table. I don't know why, but to make it work, I think the SQL should be something like this. SELECT licenses0_.ID as ID1_, licenses0_.ID as ID2_0_, licenses0_1_.CustomerID as CustomerID7_0_, FROM n2item licenses0_ inner join License licenses0_1_ on licenses0_.ID = licenses0_1_.ItemID WHERE licenses0_1_.CustomerID = 12 /* @p0 */ Could any one point out what's wrong with my mappings? And how can I get the correct licenses of one customer? Thanks in advance.

    Read the article

  • NHibernate 2.1.2 in medium trust.

    - by John
    I'm trying to configure nhibernate 2.1.2 to run in medium trust, without any luck. I have tried follwing the suggestions to run in medium trust and pre-generating the proxies. I then tried to remove all references to lazy loading setting the default-lazy="false" on all classes and bags. However this threw an exception asking me to configure the proxyfactory.factory_class None of these methds worked as they kept throwing generic security exceptions or throwing easying that libraries do not allow AllowPartiallyTrustedCallers. Am I using the wrong version of NHibernate if I want to run in medium trust? Is there a specific set of binaries, or source, which I should be using.

    Read the article

  • Add objects to association in OnPreInsert, OnPreUpdate

    - by Dmitriy Nagirnyak
    Hi, I have an event listener (for Audit Logs) which needs to append audit log entries to the association of the object: public Company : IAuditable { // Other stuff removed for bravety IAuditLog IAuditable.CreateEntry() { var entry = new CompanyAudit(); this.auditLogs.Add(entry); return entry; } public virtual IEnumerable<CompanyAudit> AuditLogs { get { return this.auditLogs } } } The AuditLogs collection is mapped with cascading: public class CompanyMap : ClassMap<Company> { public CompanyMap() { // Id and others removed fro bravety HasMany(x => x.AuditLogs).AsSet() .LazyLoad() .Access.ReadOnlyPropertyThroughCamelCaseField() .Cascade.All(); } } And the listener just asks the auditable object to create log entries so it can update them: internal class AuditEventListener : IPreInsertEventListener, IPreUpdateEventListener { public bool OnPreUpdate(PreUpdateEvent ev) { var audit = ev.Entity as IAuditable; if (audit == null) return false; Log(audit); return false; } public bool OnPreInsert(PreInsertEvent ev) { var audit = ev.Entity as IAuditable; if (audit == null) return false; Log(audit); return false; } private static void LogProperty(IAuditable auditable) { var entry = auditable.CreateAuditEntry(); entry.CreatedAt = DateTime.Now; entry.Who = GetCurrentUser(); // Might potentially execute a query. // Also other information is set for entry here } } The problem with it though is that it throws TransientObjectException when commiting the transaction: NHibernate.TransientObjectException : object references an unsaved transient instance - save the transient instance before flushing. Type: CompanyAudit, Entity: CompanyAudit at NHibernate.Engine.ForeignKeys.GetEntityIdentifierIfNotUnsaved(String entityName, Object entity, ISessionImplementor session) at NHibernate.Type.EntityType.GetIdentifier(Object value, ISessionImplementor session) at NHibernate.Type.ManyToOneType.NullSafeSet(IDbCommand st, Object value, Int32 index, Boolean[] settable, ISessionImplementor session) at NHibernate.Persister.Collection.AbstractCollectionPersister.WriteElement(IDbCommand st, Object elt, Int32 i, ISessionImplementor session) at NHibernate.Persister.Collection.AbstractCollectionPersister.PerformInsert(Object ownerId, IPersistentCollection collection, IExpectation expectation, Object entry, Int32 index, Boolean useBatch, Boolean callable, ISessionImplementor session) at NHibernate.Persister.Collection.AbstractCollectionPersister.Recreate(IPersistentCollection collection, Object id, ISessionImplementor session) at NHibernate.Action.CollectionRecreateAction.Execute() at NHibernate.Engine.ActionQueue.Execute(IExecutable executable) at NHibernate.Engine.ActionQueue.ExecuteActions(IList list) at NHibernate.Engine.ActionQueue.ExecuteActions() at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) at NHibernate.Impl.SessionImpl.Flush() at NHibernate.Transaction.AdoTransaction.Commit() As the cascading is set to All I expected NH to handle this. I also tried to modify the collection using state but pretty much the same happens. So the question is what is the last chance to modify object's associations before it gets saved? Thanks, Dmitriy.

    Read the article

  • NHibernate CreateSQLQuery data conversion from bit to boolean error

    - by RemotecUk
    Hi, Im being a bit lazy in NHibernate and using Session.CreateSqlQuery(...) instead of doing the whole thing with Lambda's. Anyway what struct me is that there seems to be a problem converting some of the types returned from (in this case the MySQL) DB into native .Net tyes. The query in question looks like this.... IList<Client> allocatableClients = Session.CreateSQLQuery( "select clients.id as Id, clients.name as Name, clients.customercode as CustomerCode, clients.superclient as SuperClient, clients.clienttypeid as ClientType " + ... ... .SetResultTransformer(new NHibernate.Transform.AliasToBeanResultTransformer(typeof(Client))).List<Client>(); The type in the database of SuperClient is a bit(1) and in the Client object the type is a bool. The error received is: System.ArgumentException: Object of type 'System.UInt64' cannot be converted to type 'System.Boolean'. It seems strange that this conversion cannot be completed. Would be greatful for any ideas. Thanks.

    Read the article

  • NHibernate IPreUpdateEventListener weird behaviour

    - by mcaaltuntas
    I am using NHibernate 2.0.1 and IPreUpdateEventListener,IPreInsertEventListener events for audit logging purposes. I have a basic entity that has a one to many relation like this. User-------Books From an ASP.NET MVC controller method i am adding a book to a user like this. Book book =new Book("LOTR"); var userBook=user.AddBook(book); After session flushing OnPreInsert event called once for newly created Book object than OnPreUpdate called for all books objects in user's books collection even they have not changed.So I am updating LastMofiedDate property of all books objects and I dont want to do this. Is this supposed behaviour of NHibernate or am I missing something?

    Read the article

  • please explain NHibernate HiLo

    - by Ben
    I'm struggling to get my head round how the HiLo generator works in NHibernate. I've read the explanation here which made things a little clearer. My understanding is that each SessionFactory retrieves the high value from the database. This improves performance because we have access to IDs without hitting the database. The explanation from the above link also states: For instance, supposing you have a "high" sequence with a current value of 35, and the "low" number is in the range 0-1023. Then the client can increment the sequence to 36 (for other clients to be able to generate keys while it's using 35) and know that keys 35/0, 35/1, 35/2, 35/3... 35/1023 are all available. How does this work in a web application as don't I only have one SessionFactory and therefore one hi value. Does this mean that in a disconnected application you can end up with duplicate (low) ids in your entity table? In my tests I used these settings: <id name="Id" unsaved-value="0"> <generator class="hilo"/> </id> I ran a test to save 100 objects. The IDs in my table went from 32768 - 32868. The next hi value was incremented to 2. Then I ran my test again and the Ids were in the range 65536 - 65636. First off, why start at 32768 and not 1, and secondly why the jump from 32868 to 65536? Now I know that my surrogate keys shouldn't have any meaning but we do use them in our application. Why can't I just have them increment nicely like a SQL Server identity field would. Finally can someone give me an explanation of how the max_lo parameter works? Is this the maximum number of low values (entity ids in my head) that can be created against the high value? This is one topic in NHibernate that I have struggled to find documentation for. I read the entire NHibernate in action book and it still doesn't go into how this works in any detail. Thanks Ben

    Read the article

  • Scalar-Valued Function in NHibernate

    - by Byron Sommardahl
    I have the following scalar function in MS SQL 2005: CREATE FUNCTION [dbo].[Distance] ( @lat1 float, @long1 float,@lat2 float, @long2 float ) RETURNS float AS BEGIN RETURN (3958*3.1415926*sqrt((@lat2-@lat1)*(@lat2-@lat1) + cos(@lat2/57.29578)*cos(@lat1/57.29578)*(@long2-@long1)*(@long2-@long1))/180); END I need to be able to call this function from my NHibernate queries. I read over this article, but I got bogged down in some details that I didn't understand right away. If you've used scalar functions with NHibernate, could you possibly give me an example of how your HBM file would look for a function like this?

    Read the article

  • ORM market analysis

    - by bonefisher
    I would like to see your experience with popular ORM tools outhere, like NHibernate, LLBLGen, EF, S2Q, Genom-e, LightSpeed, DataObjects.NET, OpenAccess, ... From my exp: - Genom-e is quiet capable of Linq & performance, dev support - EF lacks on some key features like lazy loading, Poco support, pers.ignorance... but in 4.o it may have overcome .. - DataObjects.Net so far good, althrough I found some bugs - NHibernate steep learning curve, no 100% Linq support (like in Genom-e and DataObjects.Net), but very supportive, extensible and mature

    Read the article

  • Relying on nhibernate's second level cache vs pushing objects into the session

    - by AhmetC
    I have some big entities which are frequently accessed in the same session. For example, in my application there is a reporting page which consist of dynamically generated chart images. For each chart image on this page, the client makes requests to corresponding controller and the controller generates images using some entities. I can either use asp.net's session dictionary for "caching" those entities or rely on nhibernate's second level cache support with using cached queries for example. What is your opinion? By the way I will use shared hosting, is nhibernate's second level cache hosting friendly? Thanks.

    Read the article

  • nhibernate hql date functions

    - by Russel
    Hi Im writing a notification platform using C# and NHibernate. Im having difficulties with my queries. I have a Customer entity - which contains a AssessmentCompleted Property. A notification should be sent out 21 months after certification. So my query needs to include all customers where their AssessmentCompletedDate + 21months < currentDate. How do I achieve this? Is there a month add method in nhibernate? I need to add 21 months to each AssessmentCompletedProperty...My query needs to look something like: SELECT new Notification(c.Id, c.Description, c.AssessmentCompleted + 21 FROM Cusomter c AND c.AssessmentCompleted + 21 <= :EndDate

    Read the article

  • using MEF with NHibernate and windsor

    - by Fran
    I have an ASP.net MVC application that is using NHibernate under the covers for data access. I'm using the Windsor container to handle injecting ISession references into each controller. This works great, but now I'm looking to expand my application with a pluggable architecture so that I can have a core product and specific add-ons. I found a great article on doing this with MEF. My question is how to make the Windsor container and MEF container, life/work together so that I can achieve this. There was an article (http://codebetter.com/blogs/glenn.block/archive/2009/10/31/should-i-use-mef-with-an-ioc-container.aspx) by Glenn Block that talked about this exact issue. Then end then said that the next article would show you how to do this, but there's no part 2. Has anyone created an application like this using asp.net mvc, mef, nhibernate, castle windsor?

    Read the article

  • How can I run NHibenate queries asynchronously?

    - by andrey-tsykunov
    Hello, One way to increase scalability of the server application is to run IO-bound operation (reading files, sockets, web requests, database requests etc) asynchronously. This does not mean run then in the ThreadPool which will just block threads while operation is being executed. The correct way is to use asynchronous API (BeginRead, BeginGetResponse, BeginExecuteReader etc). The problem is well described in CLR vi C# book. Here is some article about asynchronous queries in Linq to SQL. Are any ways to execute Nhibernate query asynchonously? What about Linq to NHibernate? Thank you, Andrey

    Read the article

  • NHibernate criteria query question

    - by Chris
    I have 3 related objects (Entry, GamePlay, Prize) and I'm trying to find the best way to query them for what I need using NHibernate. When a request comes in, I need to query the Entries table for a matching entry and, if found, get a) the latest game play along with the first game play that has a prize attached. Prize is a child of GamePlay and each Entry object has a GamePlays property (IList). Currently, I'm working on a method that pulls the matching Entry and eagerly loads all game plays and associated prizes, but it seems wasteful to load all game plays just to find the latest one and any that contain a prize. Right now, my query looks like this: var entry = session.CreateCriteria<Entry>() .Add(Restrictions.Eq("Phone", phone)) .AddOrder(Order.Desc("Created")) .SetFetchMode("GamePlays", FetchMode.Join) .SetMaxResults(1).UniqueResult<Entry>(); Two problems with this: It loads all game plays up front. With 365 days of data, this could easily balloon to 300k of data per query. It doesn't eagerly load the Prize child property for each game. Therefore, my code that loops through the GamePlays list looking for a non-null Prize must make a call to load each Prize property I check. I'm not an nhibernate expert, but I know there has to be a better way to do this. Ideally, I'd like to do the following (pseudocode): entry = findEntry(phoneNumber) lastPlay = getLatestGamePlay(Entry) firstWinningPlay = getFirstWinningGamePlay(Entry) The end result of course is that I have the entry details, the latest game play, and the first winning game play. The catch is that I want to do this in as few database calls as possible, otherwise I'd just execute 3 separate queries. The object definitions look like: public class Entry { public Guid Id {get;set;} public string Phone {get;set;} public IList<GamePlay> GamePlays {get;set;} // ... other properties } public class GamePlay { public Guid Id {get;set;} public Entry Entry {get;set;} public Prize Prize {get;set;} // ... other properties } public class Prize { public Guid Id {get;set;} // ... other properties } The proper NHibernate mappings are in place, so I just need help figuring out how to set up the criteria query (not looking for HQL, don't use it).

    Read the article

  • NHibernate Criteria - How to filter on combination of properties

    - by DavGarcia
    I needed to filter a list of results using the combination of two properties. A plain SQL statement would look like this: SELECT TOP 10 * FROM Person WHERE FirstName + ' ' + LastName LIKE '%' + @Term + '%' The ICriteria in NHibernate that I ended up using was: ICriteria criteria = Session.CreateCriteria(typeof(Person)); criteria.Add(Expression.Sql( "FirstName + ' ' + LastName LIKE ?", "%" + term + "%", NHibernateUtil.String)); criteria.SetMaxResults(10); It works perfectly, but I'm not sure if it is the ideal solution since I'm still learning about NHibernate's Criteria API. What are the recommended alternatives? Is there something besides Expression.Sql that would perform the same operation? I tried Expression.Like but couldn't figure out how to combine the first and last names. Should I map a FullName property to the formula "FirstName + ' ' + LastName" in the mapping class? Should I create a read only FullName property on the domain object then map it to a column?

    Read the article

  • Relying on nhibernate's second level cache vs pushing objects into asp.net session

    - by AhmetC
    I have some big entities which are frequently accessed in the same session. For example, in my application there is a reporting page which consist of dynamically generated chart images. For each chart image on this page, the client makes requests to corresponding controller and the controller generates images using some entities. I can either use asp.net's session dictionary for "caching" those entities or rely on nhibernate's second level cache support with using cached queries for example. What is your opinion? By the way I will use shared hosting, is nhibernate's second level cache hosting friendly? Thanks.

    Read the article

  • How to add objects to association in OnPreInsert, OnPreUpdate

    - by Dmitriy Nagirnyak
    Hi, I have an event listener (for Audit Logs) which needs to append audit log entries to the association of the object: public Company : IAuditable { // Other stuff removed for bravety IAuditLog IAuditable.CreateEntry() { var entry = new CompanyAudit(); this.auditLogs.Add(entry); return entry; } public virtual IEnumerable<CompanyAudit> AuditLogs { get { return this.auditLogs } } } The AuditLogs collection is mapped with cascading: public class CompanyMap : ClassMap<Company> { public CompanyMap() { // Id and others removed fro bravety HasMany(x => x.AuditLogs).AsSet() .LazyLoad() .Access.ReadOnlyPropertyThroughCamelCaseField() .Cascade.All(); } } And the listener just asks the auditable object to create log entries so it can update them: internal class AuditEventListener : IPreInsertEventListener, IPreUpdateEventListener { public bool OnPreUpdate(PreUpdateEvent ev) { var audit = ev.Entity as IAuditable; if (audit == null) return false; Log(audit); return false; } public bool OnPreInsert(PreInsertEvent ev) { var audit = ev.Entity as IAuditable; if (audit == null) return false; Log(audit); return false; } private static void LogProperty(IAuditable auditable) { var entry = auditable.CreateAuditEntry(); entry.CreatedAt = DateTime.Now; entry.Who = GetCurrentUser(); // Might potentially execute a query. // Also other information is set for entry here } } The problem with it though is that it throws TransientObjectException when commiting the transaction: NHibernate.TransientObjectException : object references an unsaved transient instance - save the transient instance before flushing. Type: PropConnect.Model.UserAuditLog, Entity: PropConnect.Model.UserAuditLog at NHibernate.Engine.ForeignKeys.GetEntityIdentifierIfNotUnsaved(String entityName, Object entity, ISessionImplementor session) at NHibernate.Type.EntityType.GetIdentifier(Object value, ISessionImplementor session) at NHibernate.Type.ManyToOneType.NullSafeSet(IDbCommand st, Object value, Int32 index, Boolean[] settable, ISessionImplementor session) at NHibernate.Persister.Collection.AbstractCollectionPersister.WriteElement(IDbCommand st, Object elt, Int32 i, ISessionImplementor session) at NHibernate.Persister.Collection.AbstractCollectionPersister.PerformInsert(Object ownerId, IPersistentCollection collection, IExpectation expectation, Object entry, Int32 index, Boolean useBatch, Boolean callable, ISessionImplementor session) at NHibernate.Persister.Collection.AbstractCollectionPersister.Recreate(IPersistentCollection collection, Object id, ISessionImplementor session) at NHibernate.Action.CollectionRecreateAction.Execute() at NHibernate.Engine.ActionQueue.Execute(IExecutable executable) at NHibernate.Engine.ActionQueue.ExecuteActions(IList list) at NHibernate.Engine.ActionQueue.ExecuteActions() at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) at NHibernate.Impl.SessionImpl.Flush() at NHibernate.Transaction.AdoTransaction.Commit() As the cascading is set to All I expected NH to handle this. I also tried to modify the collection using state but pretty much the same happens. So the question is what is the last chance to modify object's associations before it gets saved? Thanks, Dmitriy.

    Read the article

  • nHibernate HQL dynamic Instantiation question

    - by Rey
    Hello all, I can't find what's going on with the following nHibernate HQL. here's my VB.Net code: Return _Session.GetNamedQuery("PersonAnthroSummary").SetInt32(0, 2).UniqueResult() My Named Query: <sql-query name="PersonAnthroSummary"> select New PersonAnthroSummary( Anthro.Height, Anthro.Weight ) from PersonAnthroContact as Anthro where Anthro.ID = ? </sql-query> and i am importing the DTO class: <import class="xxxxxxx.DataServices.PersonAnthroSummary, xxxxxxxxx.DataServices"/> PersonAnthroSummary has a constructor that will take height and weight arguments. when i test this, nHibernate throwing following exception: {"Incorrect syntax near 'Anthro'."} and generated QueryString is: "select New PersonAnthroSummary( Anthro.Height, Anthro.Weight ) from PersonAnthroContact as Anthro where Anthro.ID = @p0" Can some one tell me what i'm doing wrong here?

    Read the article

  • Global find object references in NHibernate

    - by Miral
    Is it possible to perform a global reversed-find on NHibernate-managed objects? Specifically, I have a persistent class called "Io". There are a huge number of fields across multiple tables which can potentially contain an object of that type. Is there a way (given a specific instance of an Io object), to retrieve a list of objects (of any type) that actually do reference that specific object? (Bonus points if it can identify which specific fields actually contain the reference, but that's not critical.) Since the NHibernate mappings define all the links (and the underlying database has corresponding foreign key links), there ought to be some way to do it.

    Read the article

  • NHibernate, the Parallel Framework, and SQL Server

    - by andy
    hey guys, we have a loop that: 1.Loops over several thousand xml files. Altogether we're parsing millions of "user" nodes. 2.In each iteration we parse a "user" xml, do custom deserialization 3.finally, in each iteration, we send our object to nhibernate for saving. We use: .SaveOrUpdateAndFlush(user); This is a lengthy process, and we thought it would be a perfect candidate for testing out the .NET 4.0 Parallel libraries. So we wrapped the loop in a: Parallel.ForEach(); After doing this, we start getting "random" Timeout Exceptions from SQL Server, and finally, after leaving it running all night, OutOfMemory unhandled exceptions. I haven't done deep debugging on this yet, but what do you guys think. Is this simply a limitation of SQL Server, or could it be our NHibernate setup, or what? cheers andy

    Read the article

  • No persister for: <ClassName> issue with Fluent NHibernate

    - by Amit
    I have following code: //AutoMapConfig.cs using System; using FluentNHibernate.Automapping; namespace SimpleFNH.AutoMap { public class AutoMapConfig : DefaultAutomappingConfiguration { public override bool ShouldMap(Type type) { return type.Namespace == "Examples.FirstAutomappedProject.Entities"; } } } //CascadeConvention.cs using FluentNHibernate.Conventions; using FluentNHibernate.Conventions.Instances; namespace SimpleFNH.AutoMap { public class CascadeConvention : IReferenceConvention, IHasManyConvention, IHasManyToManyConvention { public void Apply(IManyToOneInstance instance) { instance.Cascade.All(); } public void Apply(IOneToManyCollectionInstance instance) { instance.Cascade.All(); } public void Apply(IManyToManyCollectionInstance instance) { instance.Cascade.All(); } } } //Item.cs namespace SimpleFNH.Entities { public class Item { public virtual long ID { get; set; } public virtual string ItemName { get; set; } public virtual string Description { get; set; } public virtual OrderItem OrderItem { get; set; } } } //OrderItem.cs namespace SimpleFNH.Entities { public class OrderItem { public virtual long ID { get; set; } public virtual int Quantity { get; set; } public virtual Item Item { get; set; } public virtual ProductOrder ProductOrder { get; set; } public virtual void AddItem(Item item) { item.OrderItem = this; } } } using System; using System.Collections.Generic; //ProductOrder.cs namespace SimpleFNH.Entities { public class ProductOrder { public virtual long ID { get; set; } public virtual DateTime OrderDate { get; set; } public virtual string CustomerName { get; set; } public virtual IList<OrderItem> OrderItems { get; set; } public ProductOrder() { OrderItems = new List<OrderItem>(); } public virtual void AddOrderItems(params OrderItem[] items) { foreach (var item in items) { OrderItems.Add(item); item.ProductOrder = this; } } } } //NHibernateRepo.cs using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate; using NHibernate.Criterion; using NHibernate.Tool.hbm2ddl; namespace SimpleFNH.Repository { public class NHibernateRepo { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) InitializeSessionFactory(); return _sessionFactory; } } private static void InitializeSessionFactory() { _sessionFactory = Fluently.Configure().Database( MsSqlConfiguration.MsSql2008.ConnectionString( @"server=Amit-PC\SQLEXPRESS;database=SimpleFNH;Trusted_Connection=True;").ShowSql()). Mappings(m => m.FluentMappings.AddFromAssemblyOf<Order>()).ExposeConfiguration( cfg => new SchemaExport(cfg).Create(true, true)).BuildSessionFactory(); } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } } //Program.cs using System; using System.Collections.Generic; using System.Linq; using SimpleFNH.Entities; using SimpleFNH.Repository; namespace SimpleFNH { class Program { static void Main(string[] args) { using (var session = NHibernateRepo.OpenSession()) { using (var transaction = session.BeginTransaction()) { var item1 = new Item { ItemName = "item 1", Description = "test 1" }; var item2 = new Item { ItemName = "item 2", Description = "test 2" }; var item3 = new Item { ItemName = "item 3", Description = "test 3" }; var orderItem1 = new OrderItem { Item = item1, Quantity = 2 }; var orderItem2 = new OrderItem { Item = item2, Quantity = 4 }; var orderItem3 = new OrderItem { Item = item3, Quantity = 5 }; var productOrder = new ProductOrder { CustomerName = "Amit", OrderDate = DateTime.Now, OrderItems = new List<OrderItem> { orderItem1, orderItem2, orderItem3 } }; productOrder.AddOrderItems(orderItem1, orderItem2, orderItem3); session.Save(productOrder); transaction.Commit(); } } using (var session = NHibernateRepo.OpenSession()) { // retreive all stores and display them using (session.BeginTransaction()) { var orders = session.CreateCriteria(typeof(ProductOrder)) .List<ProductOrder>(); foreach (var item in orders) { Console.WriteLine(item.OrderItems.First().Quantity); } } } } } } I tried many variations to get it working but i get an error saying No persister for: SimpleFNH.Entities.ProductOrder Can someone help me get it working? I wanted to create a simple program which will set a pattern for my bigger project but it is taking quite a lot of time than expected. It would be rally helpful if you can explain in simple terms on any template/pattern that i can use to get fluent nHibernate working. The above code uses auto mapping, which i tried after i tried with fluent mapping.

    Read the article

  • Arguments for moving from LINQtoSQL to Nhibernate?

    - by sah302
    Backstory: Hi all, I just spent a lot of time reading many of the LINQ vs Nhibernate threads here and on other sites. I work in a small development team of 4 people and we don't even have really any super experienced developers. We work for a small company that has a lot of technical needs but not enough developers to implement them (and hiring more is out of the question right now). Typically our projects (which individually are fairly small) have been coded separately and weren't really layered in anyway, code wasn't re-used, no class libraries, and we just use the LINQtoSQL .dbml files for our pojects, we really don't even use objects but pass around values and stuff, the only time we use objects is when inserting to a database (heck not even querying since you don't need to assign it to a type and can just bind to gridview). Despite all this as I said our company has a lot of technical needs, no one could come to us for a year and we would have plenty of work to implement requested features. Well I have decided to change that a bit first by creating class libraries and actually adding layers to our applications. I am trying to meet these guys halfway by still using LINQtoSQL as the ORM yet and still use VB as the language. However I am finding it a b***h of a time dealing with so many thing in LINQtoSQL that I found easy in Nhibernate (automatic handling of the session, criteria creation easier than expression trees, generic an dynamic querying easier etc.) So... Question: How can I convince my lead developers and other senior programmers that switching to Nhibernate is a good thing? That being in control of our domain objects is a good thing? That being able to implement interfaces is a good? I've tried exlpaining the advantages of this before but it's not understood by them because they've never programmed in a true OO & layered way. Also one of the counter arguments to this I can see is sqlMetal generates those classes automatically and therefore it saves a lot of time. I can't really counter that other than saying spending more time on infrastructure to make it more scalable and flexible is good, but they can't see how. Again, I know the features and advantages (somewhat enough I believe) of each, but I need arguments applicable to my context, hence why I provided the context. I just am not a very good arguer I guess. (Caveat: For all the LINQtoSQL lovers, I may just not be super proficient as LINQ, but I find it very cumbersome that you are required to download some extra library for dynamic queries which don't by default support guid comparisons, and I also find the way of updating entitites to be cumbersome as well in terms of data context managing, so it could just be that I suck hehe.)

    Read the article

< Previous Page | 21 22 23 24 25 26 27 28 29 30 31 32  | Next Page >