Search Results

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

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

  • NHibernate and objects with value-semantics

    - by Groo
    Problem: If I pass a class with value semantics (Equals method overridden) to NHibernate, NHibernate tries to save it to db even though it just saved an entity equal by value (but not by reference) to the database. What am I doing wrong? Here is a simplified example model for my problem: Let's say I have a Person entity and a City entity. One thread (producer) is creating new Person objects which belong to a specific existing City, and another thread (consumer) is saving them to a repository (using NHibernate as DAL). Since there is lot of objects being flushed at a time, I am using Guid.Comb id's to ensure that each insert is made using a single SQL command. City is an object with value-type semantics (equal by name only -- for this example purposes only): public class City : IEquatable<City> { public virtual Guid Id { get; private set; } public virtual string Name { get; set; } public virtual bool Equals(City other) { if (other == null) return false; return this.Name == other.Name; } public override bool Equals(object obj) { return Equals(obj as City); } public override int GetHashCode() { return this.Name.GetHashCode(); } } Fluent NH mapping is something like: public class PersonMap : ClassMap<Person> { public PersonMap() { Id(x => x.Id) .GeneratedBy.GuidComb(); References(x => x.City) .Cascade.SaveUpdate(); } } public class CityMap : ClassMap<City> { public CityMap() { Id(x => x.Id) .GeneratedBy.GuidComb(); Map(x => x.Name); } } Right now (with my current NHibernate mapping config), my consumer thread maintains a dictionary of cities and replaces their references in incoming person objects (otherwise NHibernate will see a new, non-cached City object and try to save it as well), and I need to do it for every produced Person object. Since I have implemented City class to behave like a value type, I hoped that NHibernate would compare Cities by value and not try to save them each time -- i.e. I would only need to do a lookup once per session and not care about them anymore. Is this possible, and if yes, what am I doing wrong here?

    Read the article

  • NHibernate auditing in disconnected mode

    - by Ciaran
    I'm developing an app with a Silverlight UI, transferring my domain objects over WCF and persisting them via NHibernate. I'm therefore working with NHibernate in a disconnected mode. I'm already using the NHibernate PreUpdate and PreInsert EventListeners to perform some metadata operations (updating Create/Update date, created/updated by etc) and they are working fine. I now have a requirement to perform data logging on some of my domain objects. So I will need to have an audit table that has a before-save and after-save state of certain entities. I had wanted to use the @event.Persister.OldState and @event.Persister.NewState to perform this logging, but because I am in a disconnected scenario (using different Sessions from when data is retrieved to when it is persisted), @event.Persister.OldState is null when I am saving my changes back to the database. How is anyone else doing data logging in a disconnected scenario with NHibernate?

    Read the article

  • How to query across many-to-many association in NHibernate?

    - by Splash
    I have two entities, Post and Tag. The Post entity has a collection of Tags which represents a many-to-many join between the two (that is, each post can have any number of tags and each tag can be associated with any number of posts). I am trying to retrieve all Posts which have a given tag. However, I seem to be unable to get this query right. I essentially want something which means the same as the following pseudo-HQL: from Posts p where p.Tags contains (from Tags t where t.Name = :tagName) order by p.DateTime The only thing I've found which even approaches this is a post by Ayende. However, his approach requires the entity on the other side (in my case, Tag) to have a collection showing the other end of the many-to-many. I don't have this and don't really wish to have it. I find it hard to believe this can't be done. What am I missing? My entities & mappings look like this (simplified): public class Post { public virtual int Id { get; set; } public virtual string Title { get; set; } private IList<Tag> tags = new List<Tag>(); public virtual IEnumerable<Tag> Tags { get { return tags; } } public virtual void AddTag(Tag tag) { this.tags.Add(tag); } } public class PostMap : ClassMap<Post> { public PostMap() { Id(x => x.Id).GeneratedBy.HiLo("99"); Map(x => x.Title); HasManyToMany(x => x.Tags); } } // ---- public class Tag { public virtual int Id { get; set; } public virtual string Name { get; set; } } public class TagMap : ClassMap<Tag> { public TagMap () { Id(x => x.Id).GeneratedBy.HiLo("99"); Map(x => x.Name).Unique(); } }

    Read the article

  • NHibernate cascade and generated guid ids - why are they not generated for the children on save?

    - by asgerhallas
    I do the following: var @case = new Case { Name = "test" }; // User is persistent and loaded in the same session User.AddCase(@case); // sets @case.User = User too Session.Update(User); response.CaseId = @case.Id; The cascade on User.Cases is set to All. But @case.Id is not set until the transaction is committed. Is that expected behavior? I would very much like to get the Id before committing. Can it be done?

    Read the article

  • Fluent NHibernate ExportSchema without connexion string

    - by Vince
    Hi all, I want to propose to user a way to generate database table script creation. To do this for now i use NHibernate ExportSchema bases on a NHibernate configuration generated with Fluent NHibernate this way (during my ISessionFactory creation method): FluentConfiguration configuration = Fluently.Configure(); ... Mapping conf ... configuration.Database(fluentDatabaseProvider); this.nhibernateConfiguration = configuration.BuildConfiguration(); returnSF = configuration.BuildSessionFactory(); ... Later new SchemaExport(this.nhibernateConfiguration) .SetOutputFile(filePath) .Execute(false, false, false); fluentDatabaseProvider is a FluentNHibernate IPersistenceConfigurer which is needed to get proper sql dialect for database creation. When factory is created with an existing database, everything works fine. But what i want to do is to create an NHibernate Configuration object on a selected database engine without a real database behind the scene... And i don't manage to do this. If anybody has some idea.

    Read the article

  • NHibernate: How is identity Id updated when saving a transient instance?

    - by bretddog
    If I use session-per-transaction and call: session.SaveOrUpdate(entity) corrected: session.SaveOrUpdateCopy(entity) ..and entity is a transient instance with identity-Id=0. Shall the above line automatically update the Id of the entity, and make the instance persistent? Or should it do so on transaction.Commit? Or do I have to somehow code that explicitly? Obviously the Id of the database row (new, since transient) is autogenerated and saved as some number, but I'm talking about the actual parameter instance here. Which is the business logic instance. EDIT Mappings: public class StoreMap : ClassMap<Store> { public StoreMap() { Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Name); HasMany(x => x.Staff) // 1:m .Cascade.All(); HasManyToMany(x => x.Products) // m:m .Cascade.All() .Table("StoreProduct"); } } public class EmployeeMap : ClassMap<Employee> { public EmployeeMap() { Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.FirstName); Map(x => x.LastName); References(x => x.Store); // m:1 } } public class ProductMap : ClassMap<Product> { public ProductMap() { Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Name).Length(20); Map(x => x.Price).CustomSqlType("decimal").Precision(9).Scale(2); HasManyToMany(x => x.StoresStockedIn) .Cascade.All() .Inverse() .Table("StoreProduct"); } } EDIT2 Class definitions: public class Store { public int Id { get; private set; } public string Name { get; set; } public IList<Product> Products { get; set; } public IList<Employee> Staff { get; set; } public Store() { Products = new List<Product>(); Staff = new List<Employee>(); } // AddProduct & AddEmployee is required. "NH needs you to set both sides before // it will save correctly" public void AddProduct(Product product) { product.StoresStockedIn.Add(this); Products.Add(product); } public void AddEmployee(Employee employee) { employee.Store = this; Staff.Add(employee); } } public class Employee { public int Id { get; private set; } public string FirstName { get; set; } public string LastName { get; set; } public Store Store { get; set; } } public class Product { public int Id { get; private set; } public string Name { get; set; } public decimal Price { get; set; } public IList<Store> StoresStockedIn { get; private set; } }

    Read the article

  • nhibernate sessionfactory instance more than once on web service

    - by Manuel
    Hello, i have a web service that use nhibernate. I have a singleton pattern on the repositorry library but on each call the service, it creates a new instance of the session factory wich is very expensive. What can i do? region Atributos /// <summary> /// Session /// </summary> private ISession miSession; /// <summary> /// Session Factory /// </summary> private ISessionFactory miSessionFactory; private Configuration miConfiguration = new Configuration(); private static readonly ILog log = LogManager.GetLogger(typeof(NHibernatePersistencia).Name); private static IRepositorio Repositorio; #endregion #region Constructor private NHibernatePersistencia() { //miConfiguration.Configure("hibernate.cfg.xml"); try { miConfiguration.Configure(); this.miSessionFactory = miConfiguration.BuildSessionFactory(); this.miSession = this.SessionFactory.OpenSession(); log.Debug("Se carga NHibernate"); } catch (Exception ex) { log.Error("No se pudo cargar Nhibernate " + ex.Message); throw ex; } } public static IRepositorio Instancia { get { if (Repositorio == null) { Repositorio = new NHibernatePersistencia(); } return Repositorio; } } #endregion #region Propiedades /// <summary> /// Sesion de NHibernate /// </summary> public ISession Session { get { return miSession.SessionFactory.GetCurrentSession(); } } /// <summary> /// Sesion de NHibernate /// </summary> public ISessionFactory SessionFactory { get { return this.miSessionFactory; } } #endregion In wich way can i create a single instance for all services?

    Read the article

  • How to map this class in NHibernate (not FluentNHibernate)?

    - by JMSA
    Suppose I have a database like this: This is set up to give role-wise menu permissions. Please note that, User-table has no direct relationship with Permission-table. Then how should I map this class against the database-tables? class User { public int ID { get; set; } public string Name { get; set; } public string Username { get; set; } public string Password { get; set; } public bool? IsActive { get; set; } public IList<Role> RoleItems { get; set; } public IList<Permission> PermissionItems { get; set; } public IList<string> MenuItemKeys { get; set; } } This means, (1) Every user has some Roles. (2) Every user has some Permissions (depending on to Roles). (3) Every user has some permitted MenuItemKeys (according to Permissions). How should my User.hbm.xml look like?

    Read the article

  • Many to Many delete in NHibernate two parents with common association

    - by Joshua Grippo
    I have 3 top level entities in my app: Circuit, Issue, Document Circuits can contain Documents and Issues can contain Documents. When I delete a Circuit, I want it to delete the documents associated with it, unless it is used by something else. I would like this same behavior with Issues. I have it working when the only association is in the same table in the db, but if it is in another table, then it fails due to foreign key constraints. ex 1(This will cascade properly, because there is only a foreign constraint from Circuit to Document) Document1 exists. Circuit1 exists and contains a reference to Document1. If I delete Circuit1 then it deletes Document1 with it. ex 2(This will cascade properly, because there is only a foreign constraint from Circuit to Document.) Document1 exists. Circuit1 exists and contains a reference to Document1. Circuit2 exists and contains a reference to Document1. If I delete Circuit1 then it is deleted, but Document1 is not deleted because Circuit2 exists. If I then delete Circuit2, then Document1 is deleted. ex 3(This will throw an error, because when it deletes the Circuit it sees that there are no other circuits that reference the document so it tries to delete the document. However it should not, because there is an Issue that has a foreign constraint to the document.) Document 1 exists. Circuit1 exists and contains a reference to Document1. Issue1 exists and contains a reference to Document1. If I delete Circuit1, then it fails, because it tries to delete Document1, but Issues1 still has a reference. DB: This think won't let upload an image, so here is the ERD to the DB: http://lh3.ggpht.com/_jZWhe7NXay8/TROJhOd7qlI/AAAAAAAAAGU/rkni3oEANvc/CircuitIssues.gif Model: public class Circuit { public virtual int CircuitID { get; set; } public virtual string CJON { get; set; } public virtual IList<Document> Documents { get; set; } } public class Issue { public virtual int IssueID { get; set; } public virtual string Summary { get; set; } public virtual IList<Model.Document> Documents { get; set; } } public class Document { public virtual int DocumentID { get; set; } public virtual string Data { get; set; } } Mapping Files: <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model" assembly="Model"> <class name="Circuit" table="Circuit"> <id name="CircuitID"> <column name="CircuitID" not-null="true"/> <generator class="identity" /> </id> <property name="CJON" column="CJON" type="string" not-null="true"/> <bag name="Documents" table="CircuitDocument" cascade="save-update,delete-orphan"> <key column="CircuitID"/> <many-to-many class="Document"> <column name="DocumentID" not-null="true"/> </many-to-many> </bag> </class> </hibernate-mapping> <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model" assembly="Model"> <class name="Issue" table="Issue"> <id name="IssueID"> <column name="IssueID" not-null="true"/> <generator class="identity" /> </id> <property name="Summary" column="Summary" type="string" not-null="true"/> <bag name="Documents" table="IssueDocument" cascade="save-update,delete-orphan"> <key column="IssueID"/> <many-to-many class="Document"> <column name="DocumentID" not-null="true"/> </many-to-many> </bag> </class> </hibernate-mapping> <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model" assembly="Model"> <class name="Document" table="Document"> <id name="DocumentID"> <column name="DocumentID" not-null="true"/> <generator class="identity" /> </id> <property name="Data" column="Data" type="string" not-null="true"/> </class> </hibernate-mapping> Code: using (ISession session = sessionFactory.OpenSession()) { var doc = new Model.Document() { Data = "Doc" }; var circuit = new Model.Circuit() { CJON = "circ" }; circuit.Documents = new List<Model.Document>(new Model.Document[] { doc }); var issue = new Model.Issue() { Summary = "iss" }; issue.Documents = new List<Model.Document>(new Model.Document[] { doc }); session.Save(circuit); session.Save(issue); session.Flush(); } using (ISession session = sessionFactory.OpenSession()) { foreach (var item in session.CreateCriteria<Model.Circuit>().List<Model.Circuit>()) { session.Delete(item); } //this flush fails, because there is a reference to a child document from issue session.Flush(); foreach (var item in session.CreateCriteria<Model.Issue>().List<Model.Issue>()) { session.Delete(item); } session.Flush(); }

    Read the article

  • Mapping Enums to Database with NHibernate/Castle ActiveRecord

    - by Mike
    There's a few other posts on mapping Enums to the DB with ActiveRecord, but none of them answer my question. I have an enum called OrderState: public enum OrderState {InQueue, Ordered, Error, Cancelled} And I have the following property on the table: [Property(NotNull = true, SqlType = "orderstate", ColumnType = "DB.EnumMapper, WebSite")] public OrderState State { get { return state; } set { state = value; } } And I have the following type class: public class EnumMapper : NHibernate.Type.EnumStringType<OrderState> { public EnumMapper() { } public override NHibernate.SqlTypes.SqlType SqlType { get { return new NHibernate.SqlTypes.SqlType(DbType.Object); } } } Now this actually works the way I want, but the problem is I have tons of enums and I don't want to create a EnumMapper class for each one of them. Isn't there some way to just tell ActiveRecord to use DbType.Object for any enum? It seems to either want to be an integer or a string, but nothing else. This one's been driving me crazy for the last 2 hours.. Mike

    Read the article

  • Multiple tables\objects in one nHibernate mapping

    - by Morrislgn
    Hi Folks I am trying to create an nHibernate mapping for a class structure like so: class UserDetails{ Guid id; User user; Role role; public User UserInfo{ get;set; } public Role UserRoles{ get;set; } public Guid ID{ Get; set; } } class User{ string name; int id; public string Name{ get;set; } public int ID{ get;set; } } class Role{ string roleName; string roleDesc; int roleId; public string RoleName{ get;set; } public string RoleDesc{ get;set; } public int RoleID{ get;set; } } The underlying DB structure is similar to the tables, but there is a linking table which links user and role using their respective IDs: UserRoleLinkTable[ identity User_Role_ID (pk) userID (FK to User table) roleid (FK to Role table) ] After playing about with nHibernate this is similar to what I want to try and achieve (but it doesnt work!): <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Admin" namespace="Admin" > <class name="UserDetails" lazy="false" table="USER"> <id name="ID"> <generator class="guid"></generator> </id> <one-to-one name="UserInfo" class="User" lazy="false" cascade="none"/> <bag name="UserRoles" inverse="false" table="Role" lazy="false" cascade="none" > <key column="Role" /> <many-to-many class="Role" column="ROLE_ID" /> </bag> </class> </hibernate-mapping> I have mappings\entities which appear to work for Role and User (used in other aspects of the project) objects but how do I pull this information into one UserDetails class? The point of the user details to be able to return all this information together as one object. Is it possible to create (for want of a better description) a container using an nHibernate mapping and map the data that way? Hopefully there is enough info to help work this out - thanks in advance for all help given! Cheers, Morris

    Read the article

  • Mapping A Sphere To A Cube

    - by petrocket
    There is a special way of mapping a cube to a sphere described here: http://mathproofs.blogspot.com/2005/07/mapping-cube-to-sphere.html It is not your basic "normalize the point and your done" approach and gives a much more evenly spaced mapping. I've tried to do the inverse of the mapping going from sphere coords to cube coords and have been unable to come up the working equations. It's a rather complex system of equations with lots of square roots. Any math geniuses want to take a crack at it? Here's the equations in c++ code: sx = x * sqrtf(1.0f - y * y * 0.5f - z * z * 0.5f + y * y * z * z / 3.0f); sy = y * sqrtf(1.0f - z * z * 0.5f - x * x * 0.5f + z * z * x * x / 3.0f); sz = z * sqrtf(1.0f - x * x * 0.5f - y * y * 0.5f + x * x * y * y / 3.0f); sx,sy,sz are the sphere coords and x,y,z are the cube coords.

    Read the article

  • nHibernate Mapping with Oracle Varchar2 Data Types

    - by Blake Blackwell
    I am new to nHibernate and having some issues getting over the learning curve. My current question involves passing a string value as a parameter to a stored sproc. The error I get is: Input string is not in correct format. My mapping file looks like this: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyCompany.MyProject.Core" namespace="MyCompany.MyProject.Core" > <class name="MyCompany.MyProject.Core.MyTable" table="My_Table" lazy="false"> <id name="Id" column="Id"></id> <property name="Name" column="Name" /> </class> <sql-query name="sp_GetTable" callable="true"> <query-param name="int_Id" type="int"/> <query-param name="vch_MyId" type="String"/> <return class="MyCompany.MyProject.Core.MyTable" /> call procedure MYPKG.MYPROC(:int_Id,:vch_MyId) </sql-query> </hibernate-mapping> When I debug nHibernate it looks like it is not an actual string value, but instead just an object value. Not sure about that though... EDIT: Adding additional code for clarification: UNIT Test List<ProcedureParameter> parms = new List<ProcedureParameter>(); parms.Add( new ProcedureParameter { ParamName = "int_Id", ParamValue = 1} ); parms.Add( new ProcedureParameter { ParamName = "vch_MyId", ParamValue = "{D18BED07-84AB-494F-A94F-6F894E284227}" } ); try { IList<MyTable> myTables = _context.GetAllByID<MyTable>( "sp_GetTable", parms ); Assert.AreNotEqual( 0, myTables.Count ); } catch( Exception ex ) { throw ex; } Data Context Method IQuery query = _session.GetNamedQuery( queryName ); foreach( ProcedureParameter parm in parms ) { query.SetParameter(parm.ParamName, "'" + parm.ParamValue + "'"); } return query.List<T>(); Come to think of it, it may have something to do with my DataContext method.

    Read the article

  • Mapping relationships from multiple databases in NHibernate

    - by mannish
    I have a multi-database application configured with NHibernate. The entities that correspond to tables from each database are in their own separate assemblies (an assembly per database if you will). I have a need/desire to relate an entity from one database to an entity of another database. Everything up to this point works as I want it to (the application handles multiple session factories, etc.). The relationship I want is many-to-one, but in reality my application only cares about one side of the relationship (for reasons that aren't relevant). The relevant entities are Project and PMProject, where a Project HAS A PMProject. When I map the many-to-one, I get the following error: NHibernate.MappingException: An association from the table PROJECTS refers to an unmapped class: SDMS.PPRM.PMProject The Project mapping itself reads (ignore the funky column naming; it's an Oracle db): <many-to-one name="PMProject" class="SDMS.PPRM.PMProject" column="PM_PROJECT_ID" cascade="none" /> In the class attribute, I'm referencing the appropriate assembly, but I get that error which seems to tell me it simply can't find the mapping file for PMProject. But that file exists (it's set as embedded resource), the session factory instantiation works without fail; so I'm at a loss on how to tell the Project mapping how/where to look for the appropriate mapping. Is there something I'm missing? A better way to go about this? Thanks in advance.

    Read the article

  • NHibernate Master-Detail and Detail Deletion.

    - by JMSA
    Role.cs public class Role { public virtual string RoleName { get; set; } public virtual bool IsActive { get; set; } public virtual IList<Permission> PermissionItems { get; set; } } Role.hbm.xml <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="POCO" namespace="POCO"> <class name="Role" table="Role"> <id name="ID" column="ID"> <generator class="native" /> </id> <property name="RoleName" column="RoleName" /> <property name="IsActive" column="IsActive" type="System.Boolean" /> <bag name="PermissionItems" table="Permission" cascade="all" inverse="true"> <key column="RoleID"/> <one-to-many class="Permission" /> </bag> </class> </hibernate-mapping> Permission.cs public class Permission { public virtual string MenuItemKey { get; set; } public virtual int RoleID { get; set; } public virtual Role Role { get; set; } } Permission.hbm.xml <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="POCO" namespace="POCO"> <class name="Permission" table="Permission"> <id name="ID" column="ID"> <generator class="native"/> </id> <property name="MenuItemKey" column="MenuItemKey" /> <property name="RoleID" column="RoleID" /> <many-to-one name="Role" column="RoleID" not-null="true" cascade="all"> </many-to-one> </class> </hibernate-mapping> Suppose, I have saved some permissions in the database by using this code: RoleRepository roleRep = new RoleRepository(); Role role = new Role(); role.Permissions = Permission.GetList(); role.SaveOrUpdate(); Now, I need this code to delete all Permissions, since role.Permissions == null. Here is the code: RoleRepository roleRep = new RoleRepository(); Role role = roleRep.Get(roleId); role.Permissions = null; role.SaveOrUpdate(); But this is not happening. What should be the correct way to cope with this situation? What/how should I change, hbm-file or persistance code?

    Read the article

  • Paging over a lazy-loaded collection with NHibernate

    - by HackedByChinese
    I read this article where Ayende states NHibernate can (compared to EF 4): Collection with lazy=”extra” – Lazy extra means that NHibernate adapts to the operations that you might run on top of your collections. That means that blog.Posts.Count will not force a load of the entire collection, but rather would create a “select count(*) from Posts where BlogId = 1” statement, and that blog.Posts.Contains() will likewise result in a single query rather than paying the price of loading the entire collection to memory. Collection filters and paged collections - this allows you to define additional filters (including paging!) on top of your entities collections, which means that you can easily page through the blog.Posts collection, and not have to load the entire thing into memory. So I decided to put together a test case. I created the cliché Blog model as a simple demonstration, with two classes as follows: public class Blog { public virtual int Id { get; private set; } public virtual string Name { get; set; } public virtual ICollection<Post> Posts { get; private set; } public virtual void AddPost(Post item) { if (Posts == null) Posts = new List<Post>(); if (!Posts.Contains(item)) Posts.Add(item); } } public class Post { public virtual int Id { get; private set; } public virtual string Title { get; set; } public virtual string Body { get; set; } public virtual Blog Blog { get; private set; } } My mappings files look like this: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true"> <class xmlns="urn:nhibernate-mapping-2.2" name="Model.Blog, TestEntityFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="Blogs"> <id name="Id" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Id" /> <generator class="identity" /> </id> <property name="Name" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Name" /> </property> <property name="Type" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Type" /> </property> <bag lazy="extra" name="Posts"> <key> <column name="Blog_Id" /> </key> <one-to-many class="Model.Post, TestEntityFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </bag> </class> </hibernate-mapping> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true"> <class xmlns="urn:nhibernate-mapping-2.2" name="Model.Post, TestEntityFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="Posts"> <id name="Id" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Id" /> <generator class="identity" /> </id> <property name="Title" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Title" /> </property> <property name="Body" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Body" /> </property> <many-to-one class="Model.Blog, TestEntityFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Blog"> <column name="Blog_id" /> </many-to-one> </class> </hibernate-mapping> My test case looks something like this: using (ISession session = Configuration.Current.CreateSession()) // this class returns a custom ISession that represents either EF4 or NHibernate { blogs = (from b in session.Linq<Blog>() where b.Name.Contains("Test") orderby b.Id select b); Console.WriteLine("# of Blogs containing 'Test': {0}", blogs.Count()); Console.WriteLine("Viewing the first 5 matching Blogs."); foreach (Blog b in blogs.Skip(0).Take(5)) { Console.WriteLine("Blog #{0} \"{1}\" has {2} Posts.", b.Id, b.Name, b.Posts.Count); Console.WriteLine("Viewing first 5 matching Posts."); foreach (Post p in b.Posts.Skip(0).Take(5)) { Console.WriteLine("Post #{0} \"{1}\" \"{2}\"", p.Id, p.Title, p.Body); } } } Using lazy="extra", the call to b.Posts.Count does do a SELECT COUNT(Id)... which is great. However, b.Posts.Skip(0).Take(5) just grabs all Posts for Blog.Id = ?id, and then LINQ on the application side is just taking the first 5 from the resulting collection. What gives?

    Read the article

  • NHibernate update using composite key

    - by Mahesh
    Hi, I have a table defnition as given below: License ClientId Type Total Used ClientId and Type together uniquely identifies a row. I have a mapping file as given below: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true"> <class name="Acumen.AAM.Domain.Model.License, Acumen.AAM.Domain" lazy="false" table="License"> <id name="ClientId" access="field" column="ClientID" /> <property name="Total" access="field" column="Total"/> <property name="Used" access="field" column="Used"/> <property name="Type" access="field" column="Type"/> </class> </hibernate-mapping> If a client used a license to create a user, I need to update the Used column in the table. As I set ClientId as the id column for this table, I am getting TooManyRowsAffectedException. could you please let me know how to set a composite key at mapping level so that NHibernate can udpate based on ClientId and Type. Something like: Update License SET Used=Used-1 WHERE ClientId='xxx' AND Type=1 Please help. Thanks, Mahesh

    Read the article

  • FluentNHibernate, getting 1 column from another table

    - by puffpio
    We're using FluentNHibernate and we have run into a problem where our object model requires data from two tables like so: public class MyModel { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual int FooId { get; set; } public virtual string FooName { get; set; } } Where there is a MyModel table that has Id, Name, and FooId as a foreign key into the Foo table. The Foo tables contains Id and FooName. This problem is very similar to another post here: http://stackoverflow.com/questions/1896645/nhibernate-join-tables-and-get-single-column-from-other-table but I am trying to figure out how to do it with FluentNHibernate. I can make the Id, Name, and FooId very easily..but mapping FooName I am having trouble with. This is my class map: public class MyModelClassMap : ClassMap<MyModel> { public MyModelClassMap() { this.Id(a => a.Id).Column("AccountId").GeneratedBy.Identity(); this.Map(a => a.Name); this.Map(a => a.FooId); // my attempt to map FooName but it doesn't work this.Join("Foo", join => join.KeyColumn("FooId").Map(a => a.FooName)); } } with that mapping I get this error: The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has invalid child element 'join' in namespace 'urn:nhibernate-mapping-2.2'. List of possible elements expected: 'joined-subclass, loader, sql-insert, sql-update, sql-delete, filter, resultset, query, sql-query' in namespace 'urn:nhibernate-mapping-2.2'. any ideas?

    Read the article

  • Nhibernate Common columns in base class

    - by sukh
    I want to design following scenario Base class (Id, Name, order, Value) 3 Derived classes derive1, derive2, derive3 inheriting properties from base There is no table for base class. And 1 table for each derived class. 3 tables have same columns. How can I create mapping file ignoring base class? Do I need to create 1 mapping file for each derived class? can I achieve this using only 1 mapping file?

    Read the article

  • XML Document straight to Stored Proc Mapping in NHibernate

    - by ZekeTheGeek
    Hello. I'm building a mechanism to take XML data from a queue and call stored procs to save the data from the XML document directly to the database. This seems like something that NHibernate could address, but of course most of the information I find discusses going from objects to database instead of another data format (XML, in this case). Is there a way to use NHibernate in this fashion or am I barking up the wrong tree? Thanks.

    Read the article

  • Need help to properly remove duplicates in NHibernate

    - by Michael D. Kirkpatrick
    Here is the problem I am having. I have a database with over 100 records in it. I am paging through the data to get 9 results at a time. When I added a check to see if items are active, it caused the results to start doubling up. A little background: "Product" is the actual product line "ProductSkus" are the actual products that exist in the product line When there is more then 1 ProductSku within Product, it causes a duplicate entry to be returned. See the NHibernate Query below: result = this.Session.CreateCriteria<Model.Product>() .Add(Expression.Eq("IsActive", true)) .AddOrder(new Order("Name", true)) .SetFirstResult(indexNumber).SetMaxResults(maxNumber) // This part of the query duplicates the products .CreateAlias("ProductSkus", "ProdSkus", JoinType.InnerJoin) .Add(Expression.Eq("ProdSkus.IsActive", true)) .CreateAlias("ProductToSubcategory", "ProdToSubcat") .CreateAlias("ProdToSubcat.ProductSubcategory", "ProdSubcat") .Add(Expression.Eq("ProdSubcat.ID", subCatId)) // This part takes out the duplicate products - Removes too many items... // Turns out that with .SetFirstResult(indexNumber).SetMaxResults(maxNumber) // it gets 9 records back then the duplicates are removed. // Example: // Total Records over 100 // Max = 9 // 4 Duplicates removed // Yields 5 records when there should be 9 // Why??? This line is ran in NHibernate on the data after it has been extracted from the SQL server. .SetResultTransformer(new NHibernate.Transform.DistinctRootEntityResultTransformer()) .List<Model.Product>(); I added the DistinctRootEntityResultTransformer to clean up the duplicates. The problem is that it pulls 9 records back that contains duplicates. DistinctRootEntityResultTransformer then cleans up the duplicates in the 9 records. I am basically needing a distinct statement to be ran on the SQL server to begin with. However, distinct on SQL is not going to work since NHibernate by default wants to add every field from every table in the select part of the statement. I am only using the fields that belong to the root table to begin with (Model.Product). If I can tell NHibernate to not add the fields to the joined tables into the select part of the statement along with adding Distinct, it would work. I use NHibernare Profiler to see the actual query: SELECT top 9 this_.ID as ID351_3_, this_.Name as Name351_3_, this_.Description as Descript3_351_3_, this_.IsActive as IsActive351_3_, this_.ManufacturerID as Manufact5_351_3_, prodskus1_.ID as ID373_0_, prodskus1_.Description as Descript2_373_0_, prodskus1_.PartNumber as PartNumber373_0_, prodskus1_.Price as Price373_0_, prodskus1_.IsKit as IsKit373_0_, prodskus1_.IsActive as IsActive373_0_, prodskus1_.IsFeaturedProduct as IsFeatur7_373_0_, prodskus1_.DateAdded as DateAdded373_0_, prodskus1_.Weight as Weight373_0_, prodskus1_.TimesViewed as TimesVi10_373_0_, prodskus1_.TimesOrdered as TimesOr11_373_0_, prodskus1_.ProductID as ProductID373_0_, prodskus1_.OverSizedBoxID as OverSiz13_373_0_, prodtosubc2_.ID as ID362_1_, prodtosubc2_.MasterSubcategory as MasterSu2_362_1_, prodtosubc2_.ProductID as ProductID362_1_, prodtosubc2_.ProductSubcategoryID as ProductS4_362_1_, prodsubcat3_.ID as ID352_2_, prodsubcat3_.Name as Name352_2_, prodsubcat3_.ProductCategoryID as ProductC3_352_2_, prodsubcat3_.ImageID as ImageID352_2_, prodsubcat3_.TriggerShow as TriggerS5_352_2_ FROM Product this_ inner join ProductSku prodskus1_ on this_.ID = prodskus1_.ProductID and (prodskus1_.IsActive = 1) inner join ProductToSubcategory prodtosubc2_ on this_.ID = prodtosubc2_.ProductID inner join ProductSubcategory prodsubcat3_ on prodtosubc2_.ProductSubcategoryID = prodsubcat3_.ID WHERE this_.IsActive = 1 /* @p0 */ and prodskus1_.IsActive = 1 /* @p1 */ and prodsubcat3_.ID = 3 /* @p2 */ ORDER BY this_.Name asc If I hand modify the query and run it directly on the SQL server I get the result set I want (I removed all the extra fields in the select section and added DISTINCT): SELECT DISTINCT top 9 this_.ID as ID351_3_, this_.Name as Name351_3_, this_.Description as Descript3_351_3_, this_.IsActive as IsActive351_3_, this_.ManufacturerID as Manufact5_351_3_, FROM Product this_ inner join ProductSku prodskus1_ on this_.ID = prodskus1_.ProductID and (prodskus1_.IsActive = 1) inner join ProductToSubcategory prodtosubc2_ on this_.ID = prodtosubc2_.ProductID inner join ProductSubcategory prodsubcat3_ on prodtosubc2_.ProductSubcategoryID = prodsubcat3_.ID WHERE this_.IsActive = 1 /* @p0 */ and prodskus1_.IsActive = 1 /* @p1 */ and prodsubcat3_.ID = 3 /* @p2 */ ORDER BY this_.Name asc The big question I now must ask is... What must I change in the NHibernate Query to ultimately get the exact same result? Thanks in advance.

    Read the article

  • For normal mapping, why can we not simply add the tangent normal to the surface normal?

    - by sebf
    I am looking at implementing bump mapping (which in all implementations I have seen is really normal mapping), and so far all I have read says that to do this, we create a matrix to convert from world-space to tangent-space, in order to transform the lights and eye direction vectors into tangent space, so that the vectors from the normal map may be used directly in place of those passed through from the vertex shader. What I do not understand though, is why we cannot just use the normalised sum of the sampled-normal vector, and the surface-normal? (assuming we already transform and pass through the surface normal for the existing lighting functions) Take the diagram below; the normal is simply the deviation from the 'reference normal' for any given coordinate system, correct? And transforming the surface normal of a mapped surface from world space to tangent space makes it equivalent to the tangent space 'reference normal', no? If so, why do we transform all lighting vectors into tangent space, instead of simply transforming the sampled tangent once in the pixel shader?

    Read the article

  • Fluent NHibernate: Entity from one table, but reference will map to another tables?

    - by Andy
    Given the following tables: Product ----------- ProductId : int (PK) ProductVersion : int ProductHistory ----------- ProductId : int (PK) ProductVersion : int (PK) Item ----------- ItemId : int (PK) ProductId : int (FK) -- ProductId + ProductVersion relates to ProductHistory ProductVersion : int (FK) And the following classes: public class Product { } public class Item { public Product Product { get; set; } } What I want to happen is this; we get a Product from the Product table, assign it to Item.Product property. But that Item.Product property should map to ProductHistory. The idea is that only the latest version of a product is in the main Product table, so we allow customers to search against that table (so that if each product has 4 versions and there are 1000 products, we only need to query though 1000 products, not 1000 products * 4 versions of each). Any idea how to acomplish this? Thanks Andy

    Read the article

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