Search Results

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

Page 21/183 | < Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >

  • NHibernate, each property is filled with a different select statement

    - by Eitan
    I'm retrieving a list of nhibernate entites which have relationships to other tables/entities. I've noticed instead of NHibernate performing JOINS and populating the properties, it retrieves the entity and then calls a select for each property. For example if a user can have many roles and I retrieve a user from the DB, Nhibernate retrieves the user and then populates the roles with another select statement. The problem is that I want to retrieve oh let's say a list of products which have various many-to-many relationships and relationships to items which have their own relationships. In the end I'm left with over a thousand DB calls to retrieve a list of 30 products. Thanks. I've also set default lazy loading to false because whenever I save the list of entities to a session, I get an error when trying to retrieve it on another page: LazyInitializationException: could not initialize proxy If anybody could shed any light I would truly appreciate it. Thanks. Eitan

    Read the article

  • FluentNhibernate dynamic runtime mappings.

    - by Paul Knopf
    I am building a framework where people will be able to save items that the created by inheriting a class of mine. I will be iterating over every type in the appdomain to find classes that I want to map to nhibernate. Every class that I find will be a subclass of the inherited type. I know how to create sub types in FluentNhibernate, but every sub type requires its own ClassMap class. Since I won't know these untill runtime, there is no way I can do that. Is there a way that I can add mappings to fluent nhibernate? Note, I know this is possible without fluent nhibernate using the Cfg class, but I don't want to manage the same code two different ways.

    Read the article

  • NHibernate many-to-many mapping

    - by Scozzard
    Hi, I am having an issue with many-to-many mapping using NHibernate. Basically I have 2 classes in my object model (Scenario and Skill) mapping to three tables in my database (Scenario, Skill and ScenarioSkill). The ScenarioSkills table just holds the IDs of the SKill and Scenario table (SkillID, ScenarioID). In the object model a Scenario has a couple of general properties and a list of associated skills (IList) that is obtained from the ScenarioSkills table. There is no associated IList of Scenarios for the Skill object. The mapping from Scenario and Skill to ScenarioSkill is a many-to-many relationship: Scenario * --- * ScenarioSkill * --- * Skill I have mapped out the lists as bags as I believe this is the best option to use from what I have read. The mappings are as follows: Within the Scenario class <bag name="Skills" table="ScenarioSkills"> <key column="ScenarioID" foreign-key="FK_ScenarioSkill_ScenarioID"/> <many-to-many class="Domain.Skill, Domain" column="SkillID" /> </bag> And within the Skill class <bag name="Scenarios" table="ScenarioSkills" inverse="true" access="noop" cascade="all"> <key column="SkillID" foreign-key="FK_ScenarioSkill_SkillID" /> <many-to-many class="Domain.Scenario, Domain" column="ScenarioID" /> </bag> Everything works fine, except when I try to delete a skill, it cannot do so as there is a reference constraint on the SkillID column of the ScenarioSkill table. Can anyone help me? I am using NHibernate 2 on an C# asp.net 3.5 web application solution.

    Read the article

  • NHibernate 3 and MySQL setup tutorial

    - by ryanzec
    Since I have given up on using the entity framework 4 as my ORM (getting it to work with MySQL and mapping table/field names like this_table/this_field to object naming like ThisTable/ThisField is POCO) I am now looking at NHibernate as it seems the the next big well know ORM for C# that probably with not die off any time soon. I am trying to lookup some tutorials and a lot of them in the configuration section have 2-2 in it and was wondering if those configuration would work with NHibernate 3? I am just curious if the 2-2 refers to the version of NHibernate or something different.

    Read the article

  • How to test soft deletion event listner without setting up NHibernate Sessions

    - by isuruceanu
    I have overridden the default NHibernate DefaultDeleteEventListener according to this source: http://nhforge.org/blogs/nhibernate/archive/2008/09/06/soft-deletes.aspx so I have protected override void DeleteEntity( IEventSource session, object entity, EntityEntry entityEntry, bool isCascadeDeleteEnabled, IEntityPersister persister, ISet transientEntities) { if (entity is ISoftDeletable) { var e = (ISoftDeletable)entity; e.DateDeleted = DateTime.Now; CascadeBeforeDelete(session, persister, entity, entityEntry, transientEntities); CascadeAfterDelete(session, persister, entity, transientEntities); } else { base.DeleteEntity(session, entity, entityEntry, isCascadeDeleteEnabled, persister, transientEntities); } } How can I test only this piece of code, without configuring an NHIbernate Session?

    Read the article

  • How do I map nested generics in NHibernate

    - by Gluip
    In NHibernate you can map generics like this <class name="Units.Parameter`1[System.Int32], Units" table="parameter_int" > </class> But how can I map a class like this? Set<T> where T is a Parameter<int> like this Set<Parameter<int>> My mapping hbm.xml looking like this fails <class name="Set`1[[Units.Parameter`1[System.Int32], Units]],Units" table="settable"/> I simplified my mappings a little to get my point accross very clearly. Basically I want NHibernate to map generic class which has has generic type parameter. Want I understand from googling around is that NHibernate is not able to parse the name to the correct type in TypeNameParser.Parse() which result in the following error when adding the mapping to the configuration System.ArgumentException: Exception of type 'System.ArgumentException' was thrown. Parameter name: typeName@31 Anybody found a way around this limitation?

    Read the article

  • How to model a relationship that NHibernate (or Hibernate) doesn’t easily support

    - by MylesRip
    I have a situation in which the ideal relationship, I believe, would involve Value Object Inheritance. This is unfortunately not supported in NHibernate so any solution I come up with will be less than perfect. Let’s say that: “Item” entities have a “Location” that can be in one of multiple different formats. These formats are completely different with no overlapping fields. We will deal with each Location in the format that is provided in the data with no attempt to convert from one format to another. Each Item has exactly one Location. “SpecialItem” is a subtype of Item, however, that is unique in that it has exactly two Locations. “Group” entities aggregate Items. “LocationGroup” is as subtype of Group. LocationGroup also has a single Location that can be in any of the formats as described above. Although I’m interested in Items by Group, I’m also interested in being able to find all items with the same Location, regardless of which group they are in. I apologize for the number of stipulations listed above, but I’m afraid that simplifying it any further wouldn’t really reflect the difficulties of the situation. Here is how the above could be diagrammed: Mapping Dilemma Diagram: (http://www.freeimagehosting.net/uploads/592ad48b1a.jpg) (I tried placing the diagram inline, but Stack Overflow won't allow that until I have accumulated more points. I understand the reasoning behind it, but it is a bit inconvenient for now.) Hmmm... Apparently I can't have multiple links either. :-( Analyzing the above, I make the following observations: I treat Locations polymorphically, referring to the supertype rather than the subtype. Logically, Locations should be “Value Objects” rather than entities since it is meaningless to differentiate between two Location objects that have all the same values. Thus equality between Locations should be based on field comparisons, not identifiers. Also, value objects should be immutable and shared references should not be allowed. Using NHibernate (or Hibernate) one would typically map value objects using the “component” keyword which would cause the fields of the class to be mapped directly into the database table that represents the containing class. Put another way, there would not be a separate “Locations” table in the database (and Locations would therefore have no identifiers). NHibernate (or Hibernate) do not currently support inheritance for value objects. My choices as I see them are: Ignore the fact that Locations should be value objects and map them as entities. This would take care of the inheritance mapping issues since NHibernate supports entity inheritance. The downside is that I then have to deal with aliasing issues. (Meaning that if multiple objects share a reference to the same Location, then changing values for one object’s Location would cause the location to change for other objects that share the reference the same Location record.) I want to avoid this if possible. Another downside is that entities are typically compared by their IDs. This would mean that two Location objects would be considered not equal even if the values of all their fields are the same. This would be invalid and unacceptable from the business perspective. Flatten Locations into a single class so that there are no longer inheritance relationships for Locations. This would allow Locations to be treated as value objects which could easily be handled by using “component” mapping in NHibernate. The downside in this case would be that the domain model becomes weaker, more fragile and less maintainable. Do some “creative” mapping in the hbm files in order to force Location fields to be mapped into the containing entities’ tables without using the “component” keyword. This approach is described by Colin Jack here. My situation is more complicated than the one he describes due to the fact that SpecialItem has a second Location and the fact that a different entity, LocatedGroup, also has Locations. I could probably get it to work, but the mappings would be non-intuitive and therefore hard to understand and maintain by other developers in the future. Also, I suspect that these tricky mappings would likely not be possible using Fluent NHibernate so I would use the advantages of using that tool, at least in that situation. Surely others out there have run into similar situations. I’m hoping someone who has “been there, done that” can share some wisdom. :-) So here’s the question… Which approach should be preferred in this situation? Why?

    Read the article

  • Is it worth migrating to NHibernate 2.x from NHibernate 1.2?

    - by Amitabh
    We are using nHibernate 1.2 in a system which is not performing good. Will there be some performance improvement if we migrate to latest version of nHibernate? Overall is it a good idea to migrate to the latest version of nHibernate? EDIT: I want to use following features to improve performance. 1. Second level cache. 2. Joined Table. 3. MultiQuery to batch queries.

    Read the article

  • nhibernate subclass in code

    - by Antonio Nakic Alfirevic
    I would like to set up table-per-classhierarchy inheritance in nhibernate thru code. Everything else is set in XML mapping files except the subclasses. If i up the subclasses in xml all is well, but not from code. This is the code i use - my concrete subclass never gets created:( //the call NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration(); SetSubclass(config, typeof(TAction), typeof(tActionSub1), "Procedure"); //the method public static void SetSubclass(Configuration configuration, Type baseClass, Type subClass, string discriminatorValue) { PersistentClass persBaseClass = configuration.ClassMappings.Where(cm => cm.MappedClass == baseClass).Single(); SingleTableSubclass persSubClass = new SingleTableSubclass(persBaseClass); persSubClass.ClassName = subClass.AssemblyQualifiedName; persSubClass.DiscriminatorValue = discriminatorValue; persSubClass.EntityPersisterClass = typeof(SingleTableEntityPersister); persSubClass.ProxyInterfaceName = (subClass).AssemblyQualifiedName; persSubClass.NodeName = subClass.Name; persSubClass.EntityName = subClass.FullName; persBaseClass.AddSubclass(persSubClass); } the Xml mapping looks like this: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Riz.Pcm.Domain.BusinessObjects" assembly="Riz.Pcm.Domain"> <class name="Riz.Pcm.Domain.BusinessObjects.TAction, Riz.Pcm.Domain" table="dbo.tAction" lazy="true"> <id name="Id" column="ID"> <generator class="guid" /> </id> <discriminator type="String" formula="(select jt.Name from TJobType jt where jt.Id=JobTypeId)" insert="true" force="false"/> <many-to-one name="Session" column="SessionID" class="TSession" /> <property name="Order" column="Order1" /> <property name="ProcessStart" column="ProcessStart" /> <property name="ProcessEnd" column="ProcessEnd" /> <property name="Status" column="Status" /> <many-to-one name="JobType" column="JobTypeID" class="TJobType" /> <many-to-one name="Unit" column="UnitID" class="TUnit" /> <bag name="TActionProperties" lazy="true" cascade="all-delete-orphan" inverse="true" > <key column="ActionID"></key> <one-to-many class="TActionProperty"></one-to-many> </bag> <!--<subclass name="Riz.Pcm.Domain.tActionSub" discriminator-value="ZPower"></subclass>--> </class> </hibernate-mapping> What am I doing wrong? I can't find any examples on google:(

    Read the article

  • NHibernate : delete error

    - by MadSeb
    Hi, Model: I have a model in which one Installation can contain multiple "Computer Systems". Database: The table Installations has two columns Name and Description. The table ComputerSystems has three columsn Name, Description and InstallationId. Mappings: I have the following mapping for Installation: <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="myProgram.Core" namespace="myProgram"> <class name="Installation" table="Installations" lazy="true"> <id name="Id" column="Id" type="int"> <generator class="native" /> </id> <property name="Name" column="Name" type="string" not-null="true" /> <property name="Description" column="Description" type="string" /> <bag name="ComputerSystems" inverse="true" lazy="true" cascade="all-delete-orphan"> <key column="InstallationId" /> <one-to-many class="ComputerSystem" /> </bag> </class> </hibernate-mapping> I have the following mapping for ComputerSystem: <?xml version="1.0" encoding="utf-8"?> <id name="Id" column="ID" type="int"> <generator class="native" /> </id> <property name="Name" column="Name" type="string" not-null="true" /> <property name="Description" column="Description" type="string" /> <many-to-one name="Installation" column="InstallationID" cascade="save-update" not-null="true" /> Classes: The Installation class is: public class Installation { public virtual String Description { get; set; } public virtual String Name { get; set; } public virtual IList<ComputerSystem> ComputerSystems { get { if (_computerSystemItems== null) { lock (this) { if (_computerSystemItems== null) _computerSystemItems= new List<ComputerSystem>(); } } return _computerSystemItems; } set { _computerSystemItems= value; } } protected IList<ComputerSystem> _computerSystemItems; public Installation() { Description = ""; Name= ""; } } The ComputerSystem class is: public class ComputerSystem { public virtual String Name { get; set; } public virtual String Description { get; set; } public virtual Installation Installation { get; set; } } The issue is that I get an error when trying to delete an installation that contains a ComputerSystem. The error is: "deleted object would be re-saved by cascade (remove deleted object from associations)". Can anyone help ? Regards, Seb

    Read the article

  • NHibernate Many to Many delete all my data in the table

    - by Daoming Yang
    I would love to thank @Stefan Steinegger and @David helped me out yesterday with many-to-many mapping. I have 3 tables which are "News", "Tags" and "News_Tags" with Many-To-Many relationship and the "News_Tags" is the link table. If I delete one of the news records, the following mappings will delete all my news records which have the same tags. One thing I need to notice, I only allowed unique tag stored in the "Tag" table. This mapping make sense for me, it will delete the tag and related News records, but how can I implement a tagging system with NHibernate? Can anyone give me some suggestion? Many thanks. Daoming. News Mapping: <class name="New" table="News" lazy="false"> <id name="NewID"> <generator class="identity" /> </id> <property name="Title" type="String"></property> <property name="Description" type="String"></property> <set name="TagsList" table="New_Tags" lazy="false" inverse="true" cascade="all"> <key column="NewID" /> <many-to-many class="Tag" column="TagID" /> </set> </class> Tag Mapping: <class name="Tag" table="Tags" lazy="false"> <id name="TagID"> <generator class="identity" /> </id> <property name="TagName" type="String"></property> <property name="DateCreated" type="DateTime"></property> <!--inverse="true" has been defined in the "News mapping"--> <set name="NewsList" table="New_Tags" lazy="false" cascade="all"> <key column="TagID" /> <many-to-many class="New" column="NewID" /> </set> </class>

    Read the article

  • sharp architecture mapping error

    - by fez
    this is the error when i load product entity my code is Configuration cfg = new NHibernate.Cfg.Configuration(); ISessionFactory sessions; public MedicineController() //Construtor { cfg.Configure(); sessions = cfg.BuildSessionFactory(); } using (var session = sessions.OpenSession()) { var pGet = session.Get<Product>(0); } The Error is Unable to locate persister for the entity named 'SharpArchitecture.Domain.Product'. The persister define the persistence strategy for an entity. Possible causes: - The mapping for 'SharpArchitecture.Domain.Product' was not added to the NHibernate configuration. Thanks in advance

    Read the article

  • Interface -> Entity Mapping

    - by KiD0M4N
    Hi guys, Suppose I have a few definitions like so: public interface ICategory { int ID { get; set; } string Name { get; set; } ICategory Parent { get; set; } } public class Category : ICategory { public virtual int ID { get; set; } public virtual string Name { get; set; } public virtual ICategory Parent { get; set; } } How do I map such a scenario in NHibernate? I am trying to separate the implementation of the DAL. I am learning NHibernate. Regards, Karan

    Read the article

  • FluentNHibernate Unit Of Work / Repository Design Pattern Questions

    - by Echiban
    Hi all, I think I am at a impasse here. I have an application I built from scratch using FluentNHibernate (ORM) / SQLite (file db). I have decided to implement the Unit of Work and Repository Design pattern. I am at a point where I need to think about the end game, which will start as a WPF windows app (using MVVM) and eventually implement web services / ASP.Net as UI. Now I already created domain objects (entities) for ORM. And now I don't know how should I use it outside of ORM. Questions about it include: Should I use ORM entity objects directly as models in MVVM? If yes, do I put business logic (such as certain values must be positive and be greater than another Property) in those entity objects? It is certainly the simpler approach, and one I am leaning right now. However, will there be gotchas that would trash this plan? If the answer above is no, do I then create a new set of classes to implement business logic and use those as Models in MVVM? How would I deal with the transition between model objects and entity objects? I guess a type converter implementation would work well here. Now I followed this well written article to implement the Unit Of Work pattern. However, due to the fact that I am using FluentNHibernate instead of NHibernate, I had to bastardize the implementation of UnitOfWorkFactory. Here's my implementation: using System; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; namespace ELau.BlindsManagement.Business { public class UnitOfWorkFactory : IUnitOfWorkFactory { private static readonly string DbFilename; private static Configuration _configuration; private static ISession _currentSession; private ISessionFactory _sessionFactory; static UnitOfWorkFactory() { // arbitrary default filename DbFilename = "defaultBlindsDb.db3"; } internal UnitOfWorkFactory() { } #region IUnitOfWorkFactory Members public ISession CurrentSession { get { if (_currentSession == null) { throw new InvalidOperationException(ExceptionStringTable.Generic_NotInUnitOfWork); } return _currentSession; } set { _currentSession = value; } } public ISessionFactory SessionFactory { get { if (_sessionFactory == null) { _sessionFactory = BuildSessionFactory(); } return _sessionFactory; } } public Configuration Configuration { get { if (_configuration == null) { Fluently.Configure().ExposeConfiguration(c => _configuration = c); } return _configuration; } } public IUnitOfWork Create() { ISession session = CreateSession(); session.FlushMode = FlushMode.Commit; _currentSession = session; return new UnitOfWorkImplementor(this, session); } public void DisposeUnitOfWork(UnitOfWorkImplementor adapter) { CurrentSession = null; UnitOfWork.DisposeUnitOfWork(adapter); } #endregion public ISession CreateSession() { return SessionFactory.OpenSession(); } public IStatelessSession CreateStatelessSession() { return SessionFactory.OpenStatelessSession(); } private static ISessionFactory BuildSessionFactory() { ISessionFactory result = Fluently.Configure() .Database( SQLiteConfiguration.Standard .UsingFile(DbFilename) ) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UnitOfWorkFactory>()) .ExposeConfiguration(BuildSchema) .BuildSessionFactory(); return result; } private static void BuildSchema(Configuration config) { // this NHibernate tool takes a configuration (with mapping info in) // and exports a database schema from it _configuration = config; new SchemaExport(_configuration).Create(false, true); } } } I know that this implementation is flawed because a few tests pass when run individually, but when all tests are run, it would fail for some unknown reason. Whoever wants to help me out with this one, given its complexity, please contact me by private message. I am willing to send some $$$ by Paypal to someone who can address the issue and provide solid explanation. I am new to ORM, so any assistance is appreciated.

    Read the article

  • Dozer deep mapping not working

    - by user363900
    I am trying to use dozer to map between classes. I have a source class that looks like this: public class initRequest{ protected String id; protected String[] details } I have a destination class that looks like this: public class initResponse{ protected String id; protected DetailsObject detObj; } public class DetailsObject{ protected List<String> details; } So essentially i want the string in the details array to be populated into the List in the Details object. I have tried a mapping like this: <mapping wildcard="true" > <class-a>com.starwood.valhalla.sgpms.dto.InitiateSynchronizationDTO</class-a> <class-b>com.starwood.valhalla.psi.sgpms.dto.InitiateSynchronizationDTO</class-b> <field> <a is-accessible="true">reservations</a> <b is-accessible="true">reservations.confirmationNum</b> </field> </mapping> But I get this error: Exception in thread "main" net.sf.dozer.util.mapping.MappingException: java.lang.NoSuchFieldException: reservations.confirmationNum at net.sf.dozer.util.mapping.util.MappingUtils.throwMappingException(MappingUtils.java:91) at net.sf.dozer.util.mapping.propertydescriptor.FieldPropertyDescriptor.<init>(FieldPropertyDescriptor.java:43) at net.sf.dozer.util.mapping.propertydescriptor.PropertyDescriptorFactory.getPropertyDescriptor(PropertyDescriptorFactory.java:53) at net.sf.dozer.util.mapping.fieldmap.FieldMap.getDestPropertyDescriptor(FieldMap.java:370) at net.sf.dozer.util.mapping.fieldmap.FieldMap.getDestFieldType(FieldMap.java:103) at net.sf.dozer.util.mapping.util.MappingsParser.processMappings(MappingsParser.java:95) at net.sf.dozer.util.mapping.util.CustomMappingsLoader.load(CustomMappingsLoader.java:77) at net.sf.dozer.util.mapping.DozerBeanMapper.loadCustomMappings(DozerBeanMapper.java:149) at net.sf.dozer.util.mapping.DozerBeanMapper.getMappingProcessor(DozerBeanMapper.java:132) at net.sf.dozer.util.mapping.DozerBeanMapper.map(DozerBeanMapper.java:94) at com.starwood.valhalla.mte.translator.StarguestPMSIntegrationDozerAdapter.adaptInit(StarguestPMSIntegrationDozerAdapter.java:30) How can i map this so that it works?

    Read the article

  • NHibernate won't persist DateTime SqlDateTime overflow

    - by chris raethke
    I am working on an ASP.NET MVC project with NHibernate as the backend and am having some trouble getting some dates to write back to my SQL Server database tables. These date fields are NOT nullable, so the many answers here about how to setup nullable datetimes have not helped. Basically when I try to save the entity which has a DateAdded and a LastUpdated fields, I am getting a SqlDateTime overflow exception. I have had a similar problem in the past where I was trying to write a datetime field into a smalldatetime column, updating the type on the column appeared to fix the problem. My gut feeling is that its going to be some problem with the table definition or some type of incompatible data types, and the overflow exception is a bit of a bum steer. I have attached an example of the table definition and the query that NHibernate is trying to run, any help or suggestions would be greatly appreciated. CREATE TABLE [dbo].[CustomPages]( [ID] [uniqueidentifier] NOT NULL, [StoreID] [uniqueidentifier] NOT NULL, [DateAdded] [datetime] NOT NULL, [AddedByID] [uniqueidentifier] NOT NULL, [LastUpdated] [datetime] NOT NULL, [LastUpdatedByID] [uniqueidentifier] NOT NULL, [Title] [nvarchar](150) NOT NULL, [Term] [nvarchar](150) NOT NULL, [Content] [ntext] NULL ) exec sp_executesql N'INSERT INTO CustomPages (Title, Term, Content, LastUpdated, DateAdded, StoreID, LastUpdatedById, AddedById, ID) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8)',N'@p0 nvarchar(21),@p1 nvarchar(21),@p2 nvarchar(33),@p3 datetime,@p4 datetime,@p5 uniqueidentifier,@p6 uniqueidentifier,@p7 uniqueidentifier,@p8 uniqueidentifier',@p0=N'Size and Colour Chart',@p1=N'size-and-colour-chart',@p2=N'This is the size and colour chart',@p3=''2009-03-14 14:29:37:000'',@p4=''2009-03-14 14:29:37:000'',@p5='48315F9F-0E00-4654-A2C0-62FB466E529D',@p6='1480221A-605A-4D72-B0E5-E1FE72C5D43C',@p7='1480221A-605A-4D72-B0E5-E1FE72C5D43C',@p8='1E421F9E-9A00-49CF-9180-DCD22FCE7F55' In response the the answers/comments, I am using Fluent NHibernate and the generated mapping is below public CustomPageMap() { WithTable("CustomPages"); Id( x => x.ID, "ID" ) .WithUnsavedValue(Guid.Empty) . GeneratedBy.Guid(); References(x => x.Store, "StoreID"); Map(x => x.DateAdded, "DateAdded"); References(x => x.AddedBy, "AddedById"); Map(x => x.LastUpdated, "LastUpdated"); References(x => x.LastUpdatedBy, "LastUpdatedById"); Map(x => x.Title, "Title"); Map(x => x.Term, "Term"); Map(x => x.Content, "Content"); } <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false" assembly="MyNamespace.Core" namespace="MyNamespace.Core"> <class name="CustomPage" table="CustomPages" xmlns="urn:nhibernate-mapping-2.2"> <id name="ID" column="ID" type="Guid" unsaved-value="00000000-0000-0000-0000-000000000000"><generator class="guid" /></id> <property name="Title" column="Title" length="100" type="String"><column name="Title" /></property> <property name="Term" column="Term" length="100" type="String"><column name="Term" /></property> <property name="Content" column="Content" length="100" type="String"><column name="Content" /></property> <property name="LastUpdated" column="LastUpdated" type="DateTime"><column name="LastUpdated" /></property> <property name="DateAdded" column="DateAdded" type="DateTime"><column name="DateAdded" /></property> <many-to-one name="Store" column="StoreID" /><many-to-one name="LastUpdatedBy" column="LastUpdatedById" /> <many-to-one name="AddedBy" column="AddedById" /></class></hibernate-mapping>

    Read the article

  • nhibernate many to many deletes

    - by asi farran
    I have 2 classes that have a many to many relationship. What i'd like to happen is that whenever i delete one side ONLY the association records will be deleted with no concern which side i delete. simplified model: classes: class Qualification { IList<ProfessionalListing> ProfessionalListings } class ProfessionalListing { IList<Qualification> Qualifications void AddQualification(Qualification qualification) { Qualifications.Add(qualification); qualification.ProfessionalListings.Add(this); } } fluent automapping with overrides: void Override(AutoMapping<Qualification> mapping) { mapping.HasManyToMany(x => x.ProfessionalListings).Inverse(); } void Override(AutoMapping<ProfessionalListing> mapping) { mapping.HasManyToMany(x => x.Qualifications).Not.LazyLoad(); } I'm trying various combinations of cascade and inverse settings but can never get there. If i have no cascades and no inverse i get duplicated entities in my collections. Setting inverse on one side makes the duplication go away but when i try to delete a qualification i get a 'deleted object would be re-saved by cascade'. How do i do this? Should i be responsible for clearing the associations of each object i delete?

    Read the article

  • Applying the Hibernate filter attribute to a Bag with a many-to-many relationship

    - by David P
    Consider the following Hibernate mapping file: <hibernate-mapping ...> <class name="ContentPackage" table="contentPackages"> <id name="Id" column="id" type="int"><generator class="native" /></id> ... <bag name="Clips" table="contentAudVidLinks"> <key column="fk_contentPackageId"></key> <many-to-many class="Clip" column="fk_AudVidId"></many-to-many> <filter name="effectiveDate" condition=":asOfDate BETWEEN startDate and endDate" /> </bag> </class> </hibernate-mapping> When I run the following command: _session.EnableFilter("effectiveDate").SetParameter("asOfDate", DateTime.Today); IList<ContentPackage> items = _session.CreateCriteria(typeof(ContentPackage)) .Add(Restrictions.Eq("Id", id)) .List<ContentPackage>(); The resulting SQL has the WHERE clause on the intermediate mapping table (contentAudVidLinks), rather than the "Clips" table even though I have added the filter attribute to the Bag of Clips. What am I doing wrong?

    Read the article

  • Linq2SQL vs NHibernate performance (have I gone mad?)

    - by HeavyWave
    I have written the following tests to compare performance of Linq2SQL and NHibernate and I find results to be somewhat strange. Mappings are straight forward and identical for both. Both are running against a live DB. Although I'm not deleting Campaigns in case of Linq, but that shouldn't affect performance by more than 10 ms. Linq: [Test] public void Test1000ReadsWritesToAgentStateLinqPrecompiled() { Stopwatch sw = new Stopwatch(); Stopwatch swIn = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000; i++) { swIn.Reset(); swIn.Start(); ReadWriteAndDeleteAgentStateWithLinqPrecompiled(); swIn.Stop(); Console.WriteLine("Run ReadWriteAndDeleteAgentState: " + swIn.ElapsedMilliseconds + " ms"); } sw.Stop(); Console.WriteLine("Total Time: " + sw.ElapsedMilliseconds + " ms"); Console.WriteLine("Average time to execute queries: " + sw.ElapsedMilliseconds / 1000 + " ms"); } private static readonly Func<AgentDesktop3DataContext, int, EntityModel.CampaignDetail> GetCampaignById = CompiledQuery.Compile<AgentDesktop3DataContext, int, EntityModel.CampaignDetail>( (ctx, sessionId) => (from cd in ctx.CampaignDetails join a in ctx.AgentCampaigns on cd.CampaignDetailId equals a.CampaignDetailId where a.AgentStateId == sessionId select cd).FirstOrDefault()); private void ReadWriteAndDeleteAgentStateWithLinqPrecompiled() { int id = 0; using (var ctx = new AgentDesktop3DataContext()) { EntityModel.AgentState agentState = new EntityModel.AgentState(); var campaign = new EntityModel.CampaignDetail { CampaignName = "Test" }; var campaignDisposition = new EntityModel.CampaignDisposition { Code = "123" }; campaignDisposition.Description = "abc"; campaign.CampaignDispositions.Add(campaignDisposition); agentState.CallState = 3; campaign.AgentCampaigns.Add(new AgentCampaign { AgentState = agentState }); ctx.CampaignDetails.InsertOnSubmit(campaign); ctx.AgentStates.InsertOnSubmit(agentState); ctx.SubmitChanges(); id = agentState.AgentStateId; } using (var ctx = new AgentDesktop3DataContext()) { var dbAgentState = ctx.GetAgentStateById(id); Assert.IsNotNull(dbAgentState); Assert.AreEqual(dbAgentState.CallState, 3); var campaignDetails = GetCampaignById(ctx, id); Assert.AreEqual(campaignDetails.CampaignDispositions[0].Description, "abc"); } using (var ctx = new AgentDesktop3DataContext()) { ctx.DeleteSessionById(id); } } NHibernate (the loop is the same): private void ReadWriteAndDeleteAgentState() { var id = WriteAgentState().Id; StartNewTransaction(); var dbAgentState = agentStateRepository.Get(id); Assert.IsNotNull(dbAgentState); Assert.AreEqual(dbAgentState.CallState, 3); Assert.AreEqual(dbAgentState.Campaigns[0].Dispositions[0].Description, "abc"); var campaignId = dbAgentState.Campaigns[0].Id; agentStateRepository.Delete(dbAgentState); NHibernateSession.Current.Transaction.Commit(); Cleanup(campaignId); NHibernateSession.Current.BeginTransaction(); } Results: NHibernate: Total Time: 9469 ms Average time to execute 13 queries: 9 ms Linq: Total Time: 127200 ms Average time to execute 13 queries: 127 ms Linq lost by 13.5 times! Event with precompiled queries (both read queries are precompiled). This can't be right, although I expected NHibernate to be faster, this is just too big of a difference, considering mappings are identical and NHibernate actually executes more queries against the DB.

    Read the article

  • Design for XML mapping scenarios between two different systems [on hold]

    - by deepak_prn
    Mapping XML fields between two systems is a mundane routine in integration scenarios. I am trying to make the design documents look better and provide clear understanding to the developers especially when we do not use XSLT or any other IDE such as jDeveloper or eclipse plugins. I want it to be a high level design but at the same time talk in developer's language. So that there is no requirements that slip under the crack. For example, one of the scenarios goes: the store cashier sells an item, the transaction data is sent to Data management system. Now, I am writing a functional design for the scenario which deals with mapping XML fields between our system and the data management system. Question : I was wondering if some one had to deal with mapping XML fields between two systems? (without XSLT being involved) and if you used a table to represent the fields mapping (example is below) or any other visualization tool which does not break the bank ? I am trying to find out if there is a better way to represent XML mapping in your design documents. The widely accepted and used method seems to be using a simple table such as in the picture to illustrate the mapping. I am wondering if there are alternate ways/ tools to represent such as in Altova:

    Read the article

  • Failed Castle ActiveRecord TransactionScope causes future queries to be invalid

    - by mbp
    I am trying to solve an issue when using a Castle ActiveRecord TransactionScope which is rolled back. After the rollback, I am unable to query the Dog table. The "Dog.FindFirst()" line fails with "Could not perform SlicedFindAll for Dog", because it cannot insert dogMissingName. using (new SessionScope()) { try { var trans = new TransactionScope(TransactionMode.New, OnDispose.Commit); try { var dog = new Dog { Name = "Snowy" }; dog.Save(); var dogMissingName = new Dog(); dogMissingName.Save(); } catch (Exception) { trans.VoteRollBack(); throw; } finally { trans.Dispose(); } } catch (Exception ex) { var randomDog = Dog.FindFirst() Console.WriteLine("Random dog : " + randomDog.Name); } } Stacktrace is as follows: Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform SlicedFindAll for Dog ---> NHibernate.Exceptions.GenericADOException: could not insert: [Mvno.Dal.Dog#219e86fa-1081-490a-92d1-9d480171fcfd][SQL: INSERT INTO Dog (Name, Id) VALUES (?, ?)] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Name', table 'Dog'; column does not allow nulls. INSERT fails. The statement has been terminated. ved System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) ved System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) ved System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) ved System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) ved System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) ved System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) ved System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) ved System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) ved System.Data.SqlClient.SqlCommand.ExecuteNonQuery() ved NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd) ved NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation) ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) --- End of inner exception stack trace --- ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session) ved NHibernate.Action.EntityInsertAction.Execute() ved NHibernate.Engine.ActionQueue.Execute(IExecutable executable) ved NHibernate.Engine.ActionQueue.ExecuteActions(IList list) ved NHibernate.Engine.ActionQueue.ExecuteActions() ved NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) ved NHibernate.Event.Default.DefaultAutoFlushEventListener.OnAutoFlush(AutoFlushEvent event) ved NHibernate.Impl.SessionImpl.AutoFlushIfRequired(ISet`1 querySpaces) ved NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) ved NHibernate.Impl.CriteriaImpl.List(IList results) ved NHibernate.Impl.CriteriaImpl.List() ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria) --- End of inner exception stack trace --- ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria) ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, Order[] orders, ICriterion[] criteria) ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, ICriterion[] criteria) ved Castle.ActiveRecord.ActiveRecordBase`1.FindFirst(ICriterion[] criteria)

    Read the article

  • NHibernate, transactions and TransactionScope

    - by Erik
    I'm trying to find the best solution to handle transaction in a web application that uses NHibernate. We use a IHttpModule and at HttpApplication.BeginRequest we open a new session and we bind it to the HttpContext with ManagedWebSessionContext.Bind(context, session); We close and unbind the session on HttpApplication.EndRequest. In our Repository base class, we always wrapped a transaction around our SaveOrUpdate, Delete, Get methods like, according to best practice: public virtual void Save(T entity) { var session = DependencyManager.Resolve<ISession>(); using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(entity); transaction.Commit(); } } But then this doesn't work, if you need to put a transaction somewhere in e.g. a Application service to include several repository calls to Save, Delete, etc.. So what we tried is to use TransactionScope (I didn't want to write my own transactionmanager). To test that this worked, I use an outer TransactionScope that doesn't call .Complete() to force a rollback: Repository Save(): public virtual void Save(T entity) { using (TransactionScope scope = new TransactionScope()) { var session = Depe.ndencyManager.Resolve<ISession>(); session.SaveOrUpdate(entity); scope.Complete(); } } The block that uses the repository: TestEntity testEntity = new TestEntity { Text = "Test1" }; ITestRepository testRepository = DependencyManager.Resolve<ITestRepository>(); testRepository.Save(testEntity); using (var scope = new TransactionScope()) { TestEntity entityToChange = testRepository.GetById(testEntity.Id); entityToChange.Text = "TestChanged"; testRepository.Save(entityToChange); } TestEntity entityChanged = testRepository.GetById(testEntity.Id); Assert.That(entityChanged.Text, Is.EqualTo("Test1")); This doesn't work. But to me if NHibernate supports TransactionScope it would! What happens is that there is no ROLLBACK at all in the database but when the testRepository.GetById(testEntity.Id); statement is executed a UPDATE with SET Text = "TestCahgned" is fired instead (It should have been fired between BEGIN TRAN and ROLLBACK TRAN). NHibernate reads the value from the level1 cache and fires a UPDATE to the database. Not expected behaviour!? From what I understand whenever a rollback is done in the scope of NHibernate you also need to close and unbind the current session. My question is: Does anyone know of a good way to do this using TransactionScope and ManagedWebSessionContext?

    Read the article

  • Is it possible to mimic IQueryable with NHibernate?

    - by George
    Is it possible to mimic IQueryable with NHibernate? I was looking at Nhibernate docs and for what i could tell, it always returns a List of objects, that have it's attributes indexed by a integer. Ok, perfect, that works. But is there a way to retrieve objects like LINQ? With something like IQueryable? Thanks

    Read the article

  • Insert problem with Oracle using Nhibernate

    - by Orkun Balkanci
    There is a CLOB field we are trying to insert html content and sometimes we are getting an error as: ORA-01461: can bind a LONG value only for insert into a LONG column When i used nhibernate profiler and copy the query to Toad, it asked me to enter values for variables called "NBSP"! Is this means that nhibernate doesnt escape special chars? if so how can i tell it to escape special chars globally?

    Read the article

< Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >