Search Results

Search found 1981 results on 80 pages for 'fluent nhibernate'.

Page 12/80 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Custom SQL function for NHibernate dialect

    - by Kristoffer Ahl
    I want to be able to call a custom function called "recent_date" as part of my HQL. Like this: [Date] >= recent_date() I created a new dialect, inheriting from MsSql2000Dialect and specified the dialect for my configuration. public class NordicMsSql2000Dialect : MsSql2000Dialect { public NordicMsSql2000Dialect() { RegisterFunction( "recent_date", new SQLFunctionTemplate( NHibernateUtil.Date, "dateadd(day, -15, getdate())" ) ); } } var configuration = Fluently.Configure() .Database( MsSqlConfiguration.MsSql2000 .ConnectionString(c => .... ) .Cache(c => c.UseQueryCache().ProviderClass<HashtableCacheProvider>()) .Dialect<NordicMsSql2000Dialect>() ) .Mappings(m => ....) .BuildConfiguration(); When calling recent_date() I get the following error: System.Data.SqlClient.SqlException: 'recent_date' is not a recognized function name I'm using it in a where statement for a HasMany-mapping like below. HasMany(x => x.RecentValues) .Access.CamelCaseField(Prefix.Underscore) .Cascade.SaveUpdate() .Where("Date >= recent_date()"); What am I missing here?

    Read the article

  • NHibernate Linq - Duplicate Records

    - by adegiamb
    I am having a problem with duplicate blog post coming back when i run the linq statement below. The issue that a blog post can have the same tag more then once and that's causing the problem. I know when you use criteria you can do the followingcriteria.SetResultTransformer(new DistinctRootEntityResultTransformer()); How can I do the same thing with linq? List<BlogPost> result = (from blogPost in _session.Linq<BlogPost>() from tags in blogPost.Tags where tags.Tag == tag && blogPost.IsPublished && blogPost.Slug != slugToExclude orderby blogPost.DateCreated descending select blogPost).Distinct() .Skip(recordsToSkip).Take(pageSize).ToList();

    Read the article

  • How to map it? HasOne x References

    - by Felipe
    Hi everyones, I need to make a mapping One by One, and I have some doubts. I have this classes: public class DocumentType { public virtual int Id { get; set; } /* othes properties for documenttype */ public virtual DocumentConfiguration Configuration { get; set; } public DocumentType () { } } public class DocumentConfiguration { public virtual int Id { get; set; } /* some other properties for configuration */ public virtual DocumentType Type { get; set; } public DocumentConfiguration () { } } A DocumentType object has only one DocumentConfiguration, but it is not a inherits, it's only one by one and unique, to separate properties. How should be my mappings in this case ? Should I use References or HasOne ? Someone could give an example ? When I load a DocumentType object I'd like to auto load the property Configuration (in documentType). Thanks a lot guys! Cheers

    Read the article

  • NHibernate MySQL Composite-Key

    - by LnDCobra
    I am trying to create a composite key that mimicks the set of PrimaryKeys in the built in MySQL.DB table. The Db primary key is as follows: Field | Type | Null | ---------------------------------- Host | char(60) | No | Db | char(64) | No | User | char(16) | No | This is my DataBasePrivilege.hbm.xml file <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="TGS.MySQL.DataBaseObjects" namespace="TGS.MySQL.DataBaseObjects"> <class name="TGS.MySQL.DataBaseObjects.DataBasePrivilege,TGS.MySQL.DataBaseObjects" table="db"> <composite-id name="CompositeKey" class="TGS.MySQL.DataBaseObjects.DataBasePrivilegePrimaryKey, TGS.MySQL.DataBaseObjects"> <key-property name="Host" column="Host" type="char" length="60" /> <key-property name="DataBase" column="Db" type="char" length="64" /> <key-property name="User" column="User" type="char" length="16" /> </composite-id> </class> </hibernate-mapping> The following are my 2 classes for my composite key: namespace TGS.MySQL.DataBaseObjects { public class DataBasePrivilege { public virtual DataBasePrivilegePrimaryKey CompositeKey { get; set; } } public class DataBasePrivilegePrimaryKey { public string Host { get; set; } public string DataBase { get; set; } public string User { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (DataBasePrivilegePrimaryKey)) return false; return Equals((DataBasePrivilegePrimaryKey) obj); } public bool Equals(DataBasePrivilegePrimaryKey other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.Host, Host) && Equals(other.DataBase, DataBase) && Equals(other.User, User); } public override int GetHashCode() { unchecked { int result = (Host != null ? Host.GetHashCode() : 0); result = (result*397) ^ (DataBase != null ? DataBase.GetHashCode() : 0); result = (result*397) ^ (User != null ? User.GetHashCode() : 0); return result; } } } } And the following is the exception I am getting: Execute System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'TGS.MySQL.DataBaseObjects.DataBasePrivilegePrimaryKey'. at (Object , GetterCallback ) at NHibernate.Bytecode.Lightweight.AccessOptimizer.GetPropertyValues(Object target) at NHibernate.Tuple.Component.PocoComponentTuplizer.GetPropertyValues(Object component) at NHibernate.Type.ComponentType.GetPropertyValues(Object component, EntityMode entityMode) at NHibernate.Type.ComponentType.GetHashCode(Object x, EntityMode entityMode) at NHibernate.Type.ComponentType.GetHashCode(Object x, EntityMode entityMode, ISessionFactoryImplementor factory) at NHibernate.Engine.EntityKey.GenerateHashCode() at NHibernate.Engine.EntityKey..ctor(Object identifier, String rootEntityName, String entityName, IType identifierType, Boolean batchLoadable, ISessionFactoryImplementor factory, EntityMode entityMode) at NHibernate.Engine.EntityKey..ctor(Object id, IEntityPersister persister, EntityMode entityMode) at NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) at NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) at NHibernate.Impl.SessionImpl.Get(String entityName, Object id) at NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) at NHibernate.Impl.SessionImpl.Get[T](Object id) at TGS.MySQL.DataBase.DataProvider.GetDatabasePrivilegeByHostDbUser(String host, String db, String user) in C:\Documents and Settings\Michal\My Documents\Visual Studio 2008\Projects\TGS\TGS.MySQL.DataBase\DataProvider.cs:line 20 at TGS.UserAccountControl.UserAccountManager.GetDatabasePrivilegeByHostDbUser(String host, String db, String user) in C:\Documents and Settings\Michal\My Documents\Visual Studio 2008\Projects\TGS\TGS.UserAccountControl\UserAccountManager.cs:line 10 at TGS.UserAccountControlTest.UserAccountManagerTest.CanGetDataBasePrivilegeByHostDbUser() in C:\Documents and Settings\Michal\My Documents\Visual Studio 2008\Projects\TGS\TGS.UserAccountControlTest\UserAccountManagerTest.cs:line 12 I am new to NHibernate and any help would be appreciated. I just can't see where it is getting the object[] from? Is the composite key supposed to be object[]?

    Read the article

  • NHibernate unmapped class exception

    - by John Prideaux
    I am trying to implement a one-to-many relationship using NHibernate 2.1.2 but keep getting "Association references unmapped class" exceptions. I have verified that my hbm.xml files are embedded resource. Here are my classes and mappings. Any ideas? public class OrderStatus { public virtual decimal MainCommit { get; set; } public virtual decimal CommitNumber { get; set; } public virtual string InvoiceNumber { get; set; } public virtual string ShipTo { get; set; } public virtual string CustomerOrderNumber { get; set; } public virtual string Station { get; set; } public virtual DateTime RequestedShipDate { get; set; } public virtual decimal EstimatedValue { get; set; } public virtual decimal EstimatedWeight { get; set; } public virtual string Customer { get; set; } public virtual DateTime InvoiceDate { get; set; } public virtual ICollection<Promise> Promises { get; set; } } <class name="AladdinDb.Models.OrderStatus, AladdinDb" table="vorder_status"> <id name="CommitNumber" type="decimal" column="commit_no"> <generator class="assigned"> <param name="property"> Plan </param> </generator> </id> <property name="MainCommit" column="main_commit" type="decimal" /> <property name="InvoiceNumber" column="invoice_no" type="string" /> <property name="ShipTo" column="ship_to" type ="string"/> <property name="CustomerOrderNumber" column="cust_order_no" type="string" /> <property name="Station" column="station" type="string" /> <property name="RequestedShipDate" column="req_ship_date" type="DateTime" /> <property name="EstimatedValue" column="estimated_value" type="decimal"/> <property name="EstimatedWeight" column="estimated_weight" type="decimal" /> <property name="Customer" column="customer" type="string" /> <property name="InvoiceDate" column="invoice_date" /> <set name="Promises"> <key column="commit_no"></key> <one-to-many class="Promise" /> </set> </class> public class Promise { public virtual decimal CommitNumber { get; set; } public virtual DateTime PromiseDate { get; set; } public virtual string WhoAsked { get; set; } public virtual string WhoGave { get; set; } public virtual string Iffy { get; set; } } <class name="AladdinDb.Models.Promise, AladdinDb" table="promise"> <id name="CommitNumber" type="decimal" column="commit_no"> <generator class="assigned" /> </id> <property name="PromiseDate" column="promise_date" /> <property name="WhoAsked" column="who_asked" /> <property name="WhoGave" column="who_gave" /> <property name="Iffy" column="iffy" /> </class>

    Read the article

  • Saving child collections with NHibernate

    - by Ben
    Hi, I am in the process or learning NHibernate so bare with me. I have an Order class and a Transaction class. Order has a one to many association with transaction. The transaction table in my database has a not null constraint on the OrderId foreign key. Order class: public class Order { public virtual Guid Id { get; set; } public virtual DateTime CreatedOn { get; set; } public virtual decimal Total { get; set; } public virtual ICollection<Transaction> Transactions { get; set; } public Order() { Transactions = new HashSet<Transaction>(); } } Order Mapping: <class name="Order" table="Orders"> <cache usage="read-write"/> <id name="Id"> <generator class="guid"/> </id> <property name="CreatedOn" type="datetime"/> <property name="Total" type="decimal"/> <set name="Transactions" table="Transactions" lazy="false" inverse="true"> <key column="OrderId"/> <one-to-many class="Transaction"/> </set> Transaction Class: public class Transaction { public virtual Guid Id { get; set; } public virtual DateTime ExecutedOn { get; set; } public virtual bool Success { get; set; } public virtual Order Order { get; set; } } Transaction Mapping: <class name="Transaction" table="Transactions"> <cache usage="read-write"/> <id name="Id" column="Id" type="Guid"> <generator class="guid"/> </id> <property name="ExecutedOn" type="datetime"/> <property name="Success" type="bool"/> <many-to-one name="Order" class="Order" column="OrderId" not-null="true"/> Really I don't want a bidirectional association. There is no need for my transaction objects to reference their order object directly (I just need to access the transactions of an order). However, I had to add this so that Order.Transactions is persisted to the database: Repository: public void Update(Order entity) { using (ISession session = NHibernateHelper.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.Update(entity); foreach (var tx in entity.Transactions) { tx.Order = entity; session.SaveOrUpdate(tx); } transaction.Commit(); } } } My problem is that this will then issue an update for every transaction on the order collection (regardless of whether it has changed or not). What I was trying to get around was having to explicitly save the transaction before saving the order and instead just add the transactions to the order and then save the order: public void Can_add_transaction_to_existing_order() { var orderRepo = new OrderRepository(); var order = orderRepo.GetById(new Guid("aa3b5d04-c5c8-4ad9-9b3e-9ce73e488a9f")); Transaction tx = new Transaction(); tx.ExecutedOn = DateTime.Now; tx.Success = true; order.Transactions.Add(tx); orderRepo.Update(order); } Although I have found quite a few articles covering the set up of a one-to-many association, most of these discuss retrieving of data and not persisting back. Many thanks, Ben

    Read the article

  • Mixing inheritance mapping strategies in NHibernate

    - by MylesRip
    I have a rather large inheritance hierarchy in which some of the subclasses add very little and others add quite a bit. I don't want to map the entire hierarchy using either "table per class hierarchy" or "table per subclass" due to the size and complexity of the hierarchy. Ideally I'd like to mix mapping strategies such that portions of the hierarchy where the subclasses add very little are combined into a common table a la "table per class hierarchy" and subclasses that add a lot are broken out into a separate table. Using this approach, I would expect to have 2 or 3 tables with very little wasted space instead of either 1 table with lots of fields that don't apply to most of the objects, or 20+ tables, several of which would have only a couple of columns. In the NHibernate Reference Documentation version 2.1.0, I found section 8.1.4 "Mixing table per class hierarchy with table per subclass". This approach switches strategies partway down the hierarchy by using: ... <subclass ...> <join ...> <property ...> ... </join> </subclass> ... This is great in theory. In practice, though, I found that the schema was too restrictive in what was allowed inside the "join" element for me to be able to accomplish what I needed. Here is the related part of the schema definition: <xs:element name="join"> <xs:complexType> <xs:sequence> <xs:element ref="subselect" minOccurs="0" /> <xs:element ref="comment" minOccurs="0" /> <xs:element ref="key" /> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="property" /> <xs:element ref="many-to-one" /> <xs:element ref="component" /> <xs:element ref="dynamic-component" /> <xs:element ref="any" /> <xs:element ref="map" /> <xs:element ref="set" /> <xs:element ref="list" /> <xs:element ref="bag" /> <xs:element ref="idbag" /> <xs:element ref="array" /> <xs:element ref="primitive-array" /> </xs:choice> <xs:element ref="sql-insert" minOccurs="0" /> <xs:element ref="sql-update" minOccurs="0" /> <xs:element ref="sql-delete" minOccurs="0" /> </xs:sequence> <xs:attribute name="table" use="required" type="xs:string" /> <xs:attribute name="schema" type="xs:string" /> <xs:attribute name="catalog" type="xs:string" /> <xs:attribute name="subselect" type="xs:string" /> <xs:attribute name="fetch" default="join"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="join" /> <xs:enumeration value="select" /> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="inverse" default="false" type="xs:boolean"> </xs:attribute> <xs:attribute name="optional" default="false" type="xs:boolean"> </xs:attribute> </xs:complexType> </xs:element> As you can see, this allows the use of "property" child elements or "component" child elements, but not both. It also doesn't allow for "subclass" child elements to continue the hierarchy below the point at which the strategy was changed. Is there a way to accomplish this?

    Read the article

  • How do I grok NHibernate's QueryOver API?

    - by Brant Bobby
    I've run into the limits of what NHibernate 3.0's LINQ provider is capable of and decided it's time to learn about one of the more powerful (or at least feature-complete) options: the QueryOver API. The problem is, I have zero experience with ICriteria, and all of the tutorials I've been able to find online either: Assume I'm an ICriteria expert and simply show me how to convert ICriteria code to the new fluent interface, or Are trivial "here's how you do an inner join" examples that don't really help me understand more complex concepts like projections, subqueries, requirements, or whatever other magic the API is capable of. What should I read to really learn about QueryOver, and how to make full use of it?

    Read the article

  • NHibernate Pitfalls: Private Setter on Id Property

    - by Ricardo Peres
    Having a private setter on an entity’s id property may seem tempting: in most cases, unless you are using id generators assigned or foreign, you never have to set its value directly. However, keep this in mind: If your entity is lazy and you want to prevent people from setting its value, make the setter protected instead of private, because it will need to be accessed from subclasses of your entity (generated by NHibernate); If you use stateless sessions, you can perform some operations which, on regular sessions, require you to load an entity, without doing so, for example: 1: using (IStatelessSession session = factory.OpenStatelessSession()) 2: { 3: //delete without first loading 4: session.Delete(new Customer { Id = 1 }); 5:  6: //insert without first loading 7: session.Insert(new Order { Customer = new Customer { Id = 1 }, Product = new Product { Id = 1 } }); 8:  9: //update without first loading 10: session.Update(new Order{ Id = 1, Product = new Product{ Id = 2 }}) 11: }

    Read the article

  • Is there Linq to Nhibernate for stateless session?

    - by Jenea
    I was using regular session for loading some items from database via linq. The problem is that it caches the entities and memory load increases very much unnecessarily. Is there a way to replace session with stateless session without introducing many changes in client code?

    Read the article

  • nhibernate will not cascade delete childs

    - by marn
    The scenario is as follows, I have 3 objects (i simplified the names) named Parent, parent's child & child's child parent's child is a set in parent, and child's child is a set in child. mapping is as follows (relevant parts) parent <set name="parentset" table="pc-table" lazy="false" fetch="subselect" cascade="all-delete-orphan" inverse="true"> <key column=FK_ID_PC" on-delete="cascade"/> <one-to-many class="parentchild,parentchild-ns"/> </set> parent's child <set name="childset" table="cc-table" lazy="false" fetch="subselect" cascade="all-delete-orphan" inverse="true"> <key column="FK_ID_CC" on-delete="cascade"/> <one-to-many class="childschild,childschild-ns"/> </set> What i want to achieve is that when i delete the parent, there would be a cascade delete all the way trough to child's child. But what currently happens is this. (this is purely for mapping test purposes) getting a parent entity (works fine) IQuery query = session.CreateQuery("from Parent where ID =" + ID); IParent doc = query.UniqueResult<Parent>(); now the delete part session.Delete(doc); transaction.Commit(); After having solved the 'cannot insert null value' error with cascading and inverse i hopes this would now delete everything with this code, but only the parent is being deleted. Did i miss something in my mapping which is likely to be missed? Any hint in the right direction is more than welcome!

    Read the article

  • Nhibernate mapping

    - by john
    Hi All I am trying to map Users to each other. The senario is that users can have buddies, so it links to itself I was thinking of this public class User { public virtual Guid Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual string EmailAddress { get; set; } public virtual string Password { get; set; } public virtual DateTime? DateCreated { get; set; } **public virtual IList<User> Friends { get; set; }** public virtual bool Deleted { get; set; } } But am strugling to do the xml mapping.

    Read the article

  • NHibernate Generators

    - by Dan
    What is the best tool for generating Entity Class and/or hbm files and/or sql script for NHibernate. This list below is from http://www.hibernate.org/365.html, which is the best any why? Moregen Free, Open Source (GPL) O/R Generator that can merge into existing Visual Studio Projects. Also merges changes to generated classes. NConstruct Lite Free tool for generating NHibernate O/R mapping source code. Different databases support (Microsoft SQL Server, Oracle, Access). GENNIT NHibernate Code Generator Free/Commercial Web 2.0 code generation of NHibernate code using WYSIWYG online UML designer. GenWise Studio with NHibernate Template Commercial product; Imports your existing database and generates all XML and Classes, including factories. It can also generate a asp.net web-application for your NHibernate BO-Layer automatically. HQL Analyzer and hbm.xml GUI Editor ObjectMapper by Mats Helander is a mapping GUI with NHibernate support MyGeneration is a template-based code generator GUI. Its template library includes templates for generating mapping files and classes from a database. AndroMDA is an open-source code generation framework that uses Model Driven Architecture (MDA) to transform UML models into deployable components. It supports generation of data access layers that use NHibernate as their persistence framework. CodeSmith Template for NH NHibernate Helper Kit is a VS2005 add-in to generate classes and mapping files. NConstruct - Intelligent Software Factory Commercial product; Full .NET C# source code generation for all tiers of the information system trough simple wizard procedure. O/R mapping based on NHibernate. For both WinForms and ASP.NET 2.0.

    Read the article

  • NHibernate 2.1 MsSql2000Dialect error

    - by Daniel Dolz
    Hi. I had an old (but great) app using NHibernate 1.0.2. Worked like a charm. But then I decided to upgrade to NHibernate 2.1.2. Had to change some stuff, worked great also. Problem is, I founded out that new version works in some machines and do not work in others. What the heck? Thinking a while, I discovered that it only works in pcs with SQL 2000 installed!! previous version used to works everywhere.... Check out a piece of my exception, it has to do with mssql2000Dialect NHibernate.MappingException: Could not compile the mapping document: Datos.NH_VEN_ComprobanteBF.hbm.xml ---> NHibernate.HibernateException: Could not instantiate dialect class NHibernate.Dialect.MsSql2000Dialect ---> System.Reflection.TargetInvocationException: Se produjo una excepción en el destino de la invocación. ---> System.TypeInitializationException: Se produjo una excepción en el inicializador de tipo de 'NHibernate.NHibernateUtil'. ---> System.TypeLoadException: No se puede cargar el tipo 'System.DateTimeOffset' del ensamblado'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. en NHibernate.Type.DateTimeOffsetType.get_ReturnedClass() en NHibernate.NHibernateUtil..cctor() --- Fin del seguimiento de la pila de la excepción interna --- en NHibernate.Dialect.Dialect..ctor() en NHibernate.Dialect.MsSql2000Dialect..ctor() --- Fin del seguimiento de la pila de la excepción interna --- en System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) en System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) Could you help? Thanks!!!!

    Read the article

  • Problem with eager load polymorphic associations using Linq and NHibernate

    - by Voislav
    Is it possible to eagerly load polymorphic association using Linq and NH? For example: Company is base class, Department is inherited from Company, and Company has association Employees to the User (one-to-many) and also association to the Country (many-to-one). Here is mapping part related to inherited class (without User and Country classes): <class name="Company" discriminator-value="Company"> <id name="Id" type="int" unsaved-value="0" access="nosetter.camelcase-underscore"> <generator class="native"></generator> </id> <discriminator column="OrganizationUnit" type="string" length="10" not-null="true"/> <property name="Name" type="string" length="50" not-null="true"/> <many-to-one name="Country" class="Country" column="CountryId" not-null ="false" foreign-key="FK_Company_CountryId" access="field.camelcase-underscore" /> <set name="Departments" inverse="true" lazy="true" access="field.camelcase-underscore"> <key column="DepartmentParentId" not-null="false" foreign-key="FK_Department_DepartmentParentId"></key> <one-to-many class="Department"></one-to-many> </set> <set name="Employees" inverse="true" lazy="true" access="field.camelcase-underscore"> <key column="CompanyId" not-null="false" foreign-key="FK_User_CompanyId"></key> <one-to-many class="User"></one-to-many> </set> <subclass name="Department" extends="Company" discriminator-value="Department"> <many-to-one name="DepartmentParent" class="Company" column="DepartmentParentId" not-null ="false" foreign-key="FK_Department_DepartmentParentId" access="field.camelcase-underscore" /> </subclass> </class> I do not have problem to eagerly load any of the association on the Company: Session.Query<Company>().Where(c => c.Name == "Main Company").Fetch(c => c.Country).Single(); Session.Query<Company>().Where(c => c.Name == "Main Company").FetchMany(c => c.Employees).Single(); Also, I could eagerly load not-polymorphic association on the department: Session.Query<Department>().Where(d => d.Name == "Department 1").Fetch(d => d.DepartmentParent).Single(); But I get NullReferenceException when I try to eagerly load any of the polymorphic association (from the Department): Assert.Throws<NullReferenceException>(() => Session.Query<Department>().Where(d => d.Name == "Department 1").Fetch(d => d.Country).Single()); Assert.Throws<NullReferenceException>(() => Session.Query<Department>().Where(d => d.Name == "Department 1").FetchMany(d => d.Employees).Single()); Am I doing something wrong or this is not supported yet?

    Read the article

  • Using nhibernate <loader> element with HQL queries

    - by Matt
    Hi All I'm attempting to use an HQL query in element to load an entity based on other entities. My class is as follows public class ParentOnly { public ParentOnly(){} public virtual int Id { get; set; } public virtual string ParentObjectName { get; set; } } and the mapping looks like this <class name="ParentOnly"> <id name="Id"> <generator class="identity" /> </id> <property name="ParentObjectName" /> <loader query-ref="parentonly"/> </class> <query name="parentonly" > select new ParentOnly() from SimpleParentObject as spo where spo.Id = :id </query> The class that I am attemping to map on top of is SimpleParentObject, which has its own mapping and can be loaded and saved without problems. When I call session.Get(id) the sql runs correctly against the SimpleParentObject table, and the a ParentOnly object is instantiated (as I can step through the constructer), but only a null comes back, rather than the instantiated ParentOnly object. I can do this succesfully using a instead of the HQL, but am trying to build this in a database independent fashion. Any thoughts on how to get the and elements to return a populated ParentOnly object...? Thanks Matt

    Read the article

  • nhibernate : One to One mapping

    - by frosty
    I have the following map. I wish to map BasketItem to the class "Product". So basically when i iterate thru the basket i can get the product name <class name="BasketItem" table="User_Current_Basket"> <id name="Id" type="Int32" column="Id" unsaved-value="0"> <generator class="identity"/> </id> <property name="ProductId" column="Item_ID" type="Int32"/> <one-to-one name="Product" class="Product"></one-to-one> </class> How do specifiy that product should match BasketItem.ProductId with Product.Id Also i've read that i should avoid one-to-one and just use one-to-many? If i was to do that how do i ensure i just get one product and not a collection.

    Read the article

  • NHibernate - Mapping tagging of entities

    - by ZNS
    Hi! I've been wrecking my mind on how to get my tagging of entities to work. I'll get right into some database structuring: tblTag TagId - int32 - PK Name tblTagEntity TagId - PK EntityId - PK EntityType - string - PK tblImage ImageId - int32 - PK tblBlog BlogId - int32 - PK class Image Id EntityType { get { return "MyNamespace.Entities.Image"; } IList Tags; class Blog Id EntityType { get { return "MyNamespace.Entities.Blog"; } IList Tags; The obvious problem I have here is that EntityType is an identifer but doesn't exist in the database. If anyone could help with the this mapping I'd be very grateful.

    Read the article

  • NHibernate MySQL Mapping Set Column Type

    - by LnDCobra
    In my MySQL database, I have the following column type. Field | Type | Null | ---------------------------------- Column_priv | set('Select','Insert','Update','References') | No | And I cannot figure out what to map this to. Can anyone tell me how I can map this to something?

    Read the article

  • Nhibernate: one-to-many, based on multiple keys?

    - by e36M3
    Lets assume I have two tables Table tA ID ID2 SomeColumns Table tB ID ID2 SomeOtherColumns I am looking to create a Object let's call it ObjectA (based on tA), that will have a one-to-many relationship to ObjectB (based on tB). In my example however, I need to use the combination of ID and ID2 as the foreign key. If I was writing SQL it would look like this: select tB.* from tA, tB where tA.ID = tB.ID and tA.ID2 = tB.ID2; I know that for each ID/ID2 combination in tA I should have many rows in tB, therefor I know it's a one-to-many combination. Clearly the below set is not sufficient for such mapping as it only takes one key into account. <set name="A2" table="A2" generic="true" inverse="true" > <key column="ID" /> <one-to-many class="A2" /> </set> Thanks!

    Read the article

  • NHibernate ManyToMany Relationship Cascading AllDeleteOrphan StackOverflowException

    - by Chris
    I have two objects that have a ManyToMany relationship with one another through a mapping table. Though, when I try to save it, I get a stack overflow exception. The following is the code for the mappings: //EventMapping.cs HasManyToMany(x => x.Performers).Table("EventPerformer").Inverse().Cascade.AllDeleteOrphan().LazyLoad().ParentKeyColumn("EventId").ChildKeyColumn("PerformerId"); //PerformerMapping.cs HasManyToMany<Event>(x => x.Events).Table("EventPerformer").Inverse().Cascade.AllDeleteOrphan().LazyLoad().ParentKeyColumn("PerformerId").ChildKeyColumn("EventId"); When I change the performermapping.cs to Cascade.None() I get rid of the exception but then my Event Object doesn't have the performer I associate with it. //In a unit test, paraphrased event.Performers.Add(performer); //Event eventRepository.Save<Event>(event); eventResult = eventRepository.GetById<Event>(event.id); //Event eventResult.Performers[0]; //is null, should have performer in it How should I be writing this properly? Thanks

    Read the article

  • how to delete fk children in nhibernate

    - by frosty
    I would like to delete the ICollection PriceBreaks from Product. I'm using the following method. However they dont seem to delete. What am i missing. When i step thru. i notice that "product.PriceBreaks.Clear();" doesn't actually clear the items. Do i need to flush or something? public void RemovePriceBreak(int productId) { using (ISession session = EStore.Domain.Helpers.NHibernateHelper.OpenSession()) using (ITransaction transaction = session.BeginTransaction()) { var product = session.Get<Product>(productId); product.PriceBreaks.Clear(); session.SaveOrUpdate(product); transaction.Commit(); } } Here are my hbm files <class name="Product" table="Products"> <id name="Id" type="Int32" column="Id" unsaved-value="0"> <generator class="identity"/> </id> <property name="CompanyId" column="CompanyId" type="Int32" not-null="true" /> <property name="Name" column="Name"/> <set name="PriceBreaks" table="PriceBreaks" generic="true" cascade="all-delete-orphan" inverse="true" > <key column="ProductId" /> <one-to-many class="EStore.Domain.Model.PriceBreak, EStore.Domain" /> </set> </class> <class name="PriceBreak" table="PriceBreaks"> <id name="Id" type="Int32" column="Id" unsaved-value="0"> <generator class="identity"/> </id> <many-to-one name="Product" column="ProductId" not-null="true" cascade="all" class="EStore.Domain.Model.Product, EStore.Domain" /> </class> My Entities public class Product { public virtual int Id { get; set; } public virtual ICollection<PriceBreak> PriceBreaks { get; set; } public virtual void AddPriceBreak(PriceBreak priceBreak) { priceBreak.Product = this; PriceBreaks.Add(priceBreak); } } public class PriceBreak { public virtual int Id { get; set; } public virtual Product Product { get; set; } }

    Read the article

  • nhibernate : mapping to column other than primary key

    - by frosty
    I have the following map. My intention is for the order.BasketId to map to orderItem.BasketId. Tho when i look at the sql i see that it's mapping order.Id to orderItem.BasketId. How do i define in my order map which order property to map against basketId. It seems to default to the primary key. <property name="BasketId" column="Basket_ID" type="Int32"/> <set name="OrderItems" table="item_basket_contents" generic="true" inverse="true" > <key column="Basket_ID" /> <one-to-many class="EStore.Domain.Model.OrderItem, EStore.Domain"/> </set>

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >