Search Results

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

Page 32/183 | < Previous Page | 28 29 30 31 32 33 34 35 36 37 38 39  | Next Page >

  • Using SQL Server Views with NHibernate

    - by colinramsay
    I have a site that sells cars. On the frontend, I want to only show cars that are published, and on the backend I want to show all cars. Whether a car is published or not depends on a number of factors, so I wanted to create a view to simplify this. My question is, can I reduce duplication by dynamically telling NHibernate to sometimes use the "PublishedCar" view and something use the "AllCar" view when querying/fetching Car entities?

    Read the article

  • Nhibernate: using Expression

    - by VoodooChild
    Hello, Using nHibernate, I would like to query on an integer datatype, but its always returning the exact match. How could I write an expression that returns a list starting with the number entered? right now I am using it as: (clientNum is a long) crit.Add(Expression.Like("ClientNumber", clientNum)); //this always gives me exact matches only so I tried the following, but its complainging of a wroing type (its only expecting a string) crit.Add(Expression.Like("ClientNumber", clientNum, MatchMode.Start));

    Read the article

  • how to ensure that Nhibernate is inside a transaction when saving, updating or deleting

    - by pms1969
    I'd like to ensure that when I'm persisting any data to the database, using (Fluent)NHibernate, that the operations are executed inside a transaction. Is there anyway of checking that a transaction is active via an interceptor? Or any other eventing mechanism? More specifically, I'm using the System.Transaction.TransactionScope for transaction management, and just want to stop myself from not using it.

    Read the article

  • How to get the sql query from a NHibernate save

    - by adriaanp
    I am trying to create a type of recorded data transaction that I can replay on a different database. For example I am capturing an order into a system, when I save that I want to be able to "export" a sql script that I can run on another database to create the same order. I am using NHibernate and I am trying to catch the sql query string for the save operation to save to a file, but with no success.

    Read the article

  • NHibernate find

    - by Cory
    I have a 'Customer' table with 'FirstName' and 'LastName' columns. I have to execute a search on the 'Customer' table after 'FirstName', 'LastName' and 'FirstName + LastName' depending on a TextBox text. What's the besty way/query to implement this using NHibernate or SQL query?

    Read the article

  • NHibernate Partial Update

    - by bleevo
    Is there a way in NHibernate to start with an unproxied model var m = new Model() { ID = 1 }; m.Name = "test"; //Model also has .LastName and .Age Now save this model only updating Name without first selecting the model from the session?

    Read the article

  • Fluent NHibernate Self Referencing Many To Many

    - by Jeremy
    I have an entity called Books that can have a list of more books called RelatedBooks. The abbreviated Book entity looks something likes this: public class Book { public virtual long Id { get; private set; } public virtual IList<Book> RelatedBooks { get; set; } } Here is what the mapping looks like for this relationship HasManyToMany(x => x.RelatedBooks) .ParentKeyColumn("BookId") .ChildKeyColumn("RelatedBookId") .Table("RelatedBooks") .Cascade.SaveUpdate(); Here is a sample of the data that is then generated in the RelatedBooks table: BookId RelatedBookId 1 2 1 3 The problem happens when I Try to delete a book. If I delete the book that has an ID of 1, everything works ok and the RelatedBooks table has the two corresponding records removed. However if I try to delete the book with an ID of 3, I get the error "The DELETE statement conflicted with the REFERENCE constraint "FK5B54405174BAB605". The conflict occurred in database "Test", table "dbo.RelatedBooks", column 'RelatedBookId'". Basically what is happening is the Book cannot be deleted because the record in the RelatedBooks table that has a RelatedBookId of 3 is never deleted. How do I get that record to be deleted when I delete a book? EDIT After changing the Cascade from SaveUpdate() to All(), the same problem still exists if I try to delete the Book with an ID of 3. Also with Cascade set to All(), if delete the Book with and ID of 1, then all 3 books (ID's: 1, 2 and 3) are deleted so that won't work either. Looking at the SQL that is executed when the Book.Delete() method is called when I delete the Book with an ID of 3, it looks like the SELECT statement is looking at the wrong column (which I assume means that the SQL DELETE statment would make the same mistake, therefore never removing that record). Here is the SQL for the RelatedBook SELECT relatedboo0_.BookId as BookId3_ , relatedboo0_.RelatedBookId as RelatedB2_3_ , book1_.Id as Id14_0_ FROM RelatedBooks relatedboo0_ left outer join [Book] book1_ on relatedboo0_.RelatedBookId=book1_.Id WHERE relatedboo0_.BookId=3 The WHERE statment should look something like this for thie particular case: WHERE relatedboo0_.RelatedBookId = 3 SOLUTION Here is what I had to do to get it working for all cases Mapping: HasManyToMany(x => x.RelatedBooks) .ParentKeyColumn("BookId") .ChildKeyColumn("RelatedBookId") .Table("RelatedBooks"); Code: var book = currentSession.Get<Book>(bookId); if (book != null) { //Remove all of the Related Books book.RelatedBooks.Clear(); //Get all other books that have this book as a related book var booksWithRelated = currentSession.CreateCriteria<Book>() .CreateAlias("RelatedBooks", "br") .Add(Restrictions.Eq("br.Id", book.Id)) .List<Book>(); //Remove this book as a Related Book for all other Books foreach (var tempBook in booksWithRelated) { tempBook.RelatedBooks.Remove(book); tempBook.Save(); } //Delete the book book.Delete(); }

    Read the article

  • Using cascade in NHibernate

    - by Tyler
    I have two classes, call them Monkey and Banana, with a one-to-many bidirectional relationship. Monkey monkey = new Monkey(); Banana banana = new Banana(); monkey.Bananas.Add(banana); banana.Monkey = monkey; hibernateService.Save(banana); When I run that chunk of code, I want both monkey and banana to be persisted. However, it's only persisting both when I explicitly save the monkey and not vice versa. Initially, this made sense since only my Monkey.hbm.xml had a mapping with cascade="all". <set name="Bananas" inverse="true" cascade="all"> <key column="Id"/> <one-to-many class="Banana"/> </set> I figured I just needed to add the following to my Banana.hbm.xml file: <many-to-one name="Monkey" column="Id" cascade="all" /> Unfortunately, this resulted in a Parameter index is out of range error when I tried to run the snippet of code. I investigated this error and found this post, but I still don't see what I'm doing wrong. I have the relationship mapped once on each side as far as I can tell. For full disclosure, here are the two mapping files: Monkey.hbm.xml <class name="Monkey" table="monkies" lazy="true"> <id name="Id"> <generator class="increment" /> </id> <property name="Name" /> <set name="Bananas" inverse="true" cascade="all"> <key column="Id"/> <one-to-many class="Banana"/> </set> </class> Banana.hbm.xml <class name="Banana" table="bananas" lazy="true"> <id name="Id"> <generator class="increment" /> </id> <property name="Name" /> <many-to-one name="Monkey" column="Id" cascade="all" /> </class>

    Read the article

  • NHibernate - Retrieve specific columns and count using criteria querie

    - by Cristian Sapino
    This is my mapping file: This is the other with joined-subclass class name="CRMStradCommon.Entities.ContactoEntity,CRMStradCommon" table="contacto" dynamic-update="true" Haw can I make this query with Criteria? SELECT contacto.id, contacto.nombre, persona.apellido, COUNT(*) AS Cant FROM contacto INNER JOIN oportunidad ON contacto.id = oportunidad.dueno LEFT OUTER JOIN persona ON contacto.id = persona.id LEFT OUTER JOIN empresa ON contacto.id = empresa.id GROUP BY contacto.id, contacto.nombre, persona.apellido ORDER BY contacto.nombre, persona.apellido Thanks a lot!

    Read the article

  • FluentNHibernate - ClassMap vs IAutoMappingOverride

    - by Mendy
    In FluentNHibernate when should I use ClassMap and when IAutoMappingOverride<Entity> for my EntityMap classes. public class PostMap : ClassMap<Post> { public PostMap() { ... } } vs public class PostMap : IAutoMappingOverride<Post> { public void Override(AutoMapping<Post> mapping) { ... } }

    Read the article

  • Managing updates with NHibernate

    - by Paul Knopf
    I am aware that you can generate create scripts to generate database objects, but I am looking a way to generate an update script that compares two different schemas (two mapping files). That way I can provide my users with easy database updating from any version to the current version. Thanks!

    Read the article

  • How do I map a one-to-one value type association in an joined-subclass?

    - by David Rubin
    I've got a class hierarchy mapped using table-per-subclass, and it's been working out great: class BasicReport { ... } class SpecificReport : BasicReport { ... } With mappings: <class name="BasicReport" table="reports"> <id name="Id" column="id">...</id> <!-- some common properties --> </class> <joined-subclass name="SpecificReport" table="specificReports" extends="BasicReport"> <key column="id"/> <!-- some special properties --> </joined-subclass> So far, so good. The problem I'm struggling with is how to add a property to one of my subclasses that's both a value type for which I have an IUserType implemented and also mapped via an association: class OtherReport : BasicReport { public SpecialValue V { get; set; } } class SpecialValueUserType : IUserType { ... } What I'd like to do is: <joined-subclass name="OtherReport" table="otherReports" extends="BasicReport"> <key column="id"/> <join table="rptValues" fetch="join"> <key column="rptId"/> <property name="V" column="value" type="SpecialValueUserType"/> </join> </joined-subclass> This accurately reflects the intent, and the pre-existing database schema I'm tied to: the SpecialValue instance is a property of the OtherReport, but is stored in a separate table ("rptValues"). Unfortunately, it seems as though I can't do this, because <join> elements can't be used in <joined-subclass> mappings. <one-to-one> would require creating a class mapping for SpecialValue, which doesn't make any sense given that SpecialValue is just a meaningful scalar. So what can I do? Do I have any options? Right now I'm playing a game with sets: class OtherReport : BasicReport { public SpecialValue V { get { return _values.Count() > 0 ? _values.First() : null; } set { _values.Clear(); _values.Add(value); } } private ICollection<SpecialValue> _values; } With mapping: <joined-subclass name="OtherReport" table="otherReports" extends="BasicReport"> <key column="id"/> <set name="_values" access="field" table="rptValues" cascade="all-delete-orphan"> <key column="rptId" /> <element column="value" type="SpecialValueUserType"/> </set> </joined-subclass> Thanks in advance for the help! I've been banging my head into my desk for several days now.

    Read the article

  • NHibernate: How to-reconfigure mappings at runtime?

    - by George Mauer
    Let's get this out of the way first: I know that SessionFactory is immutable - I'm trying to change the Configuration at runtime and regenerate ISessionFactory. Specifically, I have a Customer mapped that will have some fields added to its dynamic-component node at runtime. I would like to do something like this var newSessionFactory = previousConfiguration .RemoveClassMapping(typeof(Customer)) .AddXmlString(newMappingForCustomer) .BuildSessionFactory(); However, I don't see any obvious way to remove a mapping, is there anything I can do short of regenerating the entire Configuration?

    Read the article

  • NHibernate 3.0 and FluentNHibernate, how to get up and running&hellip;.

    - by DesigningCode
    First up. Its actually really easy. I’m not very religious about my DB tech, I don’t really care, I just want something that works.  So I’m happy to consider all options if they provide an advantage, and recently I was considering jumping from NHibernate to EF 4.0.  However before ditching NHibernate and jumping to EF 4.0 I thought I should try the head version of NHibernates trunk and the Head version of FluentNHibernate. I currently have a “Repository / Unit of Work” Framework built up around these two techs.  All up it makes my life pretty simple for dealing with databases.   The problem is the current release of NHibernate + the Linq provider wasn’t too hot for our purposes.  Especially trying to plug it into older VB.NET code.   The Linq provider spat the dummy with VB.NET lambdas.  Mainly because in C# Query().Where(l => l.Name.Contains("x") || l.Name.Contains("y")).ToList(); is not the same as the VB.NET Query().Where(Function(l) l.Name.Contains("x") Or l.Name.Contains("y")).ToList VB.NET seems to spit out … well…. something different :-) so anyways… Compiling your own version of NHibernate and FluentNHibernate.  It’s actually pretty easy! First you’ll need to install tortisesvn NAnt and Git if you don’t already have them.  NHibernate first step, get the subversion trunk https://nhibernate.svn.sourceforge.net/svnroot/nhibernate/trunk/ into a directory somewhere.  eg \thirdparty\nhibernate Then use NAnt to build it.   (if you open the .sln it will show errors in that  AssemblyInfo.cs doesn’t exist ) to build it, there is a .txt document with sample command line build instructions,  I simply used :- NAnt -D:project.config=release clean build >output-release-build.log *wait* *wait* *wait* and ta da, you will have a bin directory with all the release dlls. FluentNHibernate This was pretty simple. there’s instructions here :- http://wiki.fluentnhibernate.org/Getting_started#Installation basically, with git, create a directory, and you issue the command git clone git://github.com/jagregory/fluent-nhibernate.git and wait, and soon enough you have the source. Now, from the bin directory that NHibernate spit out, take everything and dump it into the subdirectory “fluent-nhibernate\tools\NHibernate” Now, to build, you can use rake….which a ruby build system, however you can also just open the solution and build.   Which is what I did.  I had a few problems with the references which I simply re-added using the new ones.  Once built, I just took all the NHibnerate dlls, and the fluent ones and replaced my existing NHibernate / Fluent and killed off the old linq project. All I had to change is the places that used  .Linq<T>  and replace them with .Query<T>  (which was easy as I had wrapped it already to isolate my code from such changes) and hey presto, everything worked.  Even the VB.NET linq calls. I need to do some more testing as I’ve only done basic smoke tests, but its all looking pretty good, so for now, I will stick to NHibernate!

    Read the article

  • NHibernate and Stored Procedures in C#

    - by Jess Nickson
    I was recently trying and failing to set up NHibernate (v1.2) in an ASP.NET project. The aim was to execute a stored procedure and return the results, but it took several iterations for me to end up with a working solution. In this post I am simply trying to put the required code in one place, in the hope that the snippets may be useful in guiding someone else through the same process. As it is kind’ve the first time I have had to play with NHibernate, there is a good chance that this solution is sub-optimal and, as such, I am open to suggestions on how it could be improved! There are four code snippets that I required: The stored procedure that I wanted to execute The C# class representation of the results of the procedure The XML mapping file that allows NHibernate to map from C# to the procedure and back again The C# code used to run the stored procedure The Stored Procedure The procedure was designed to take a UserId and, from this, go and grab some profile data for that user. Simple, right? We just need to do a join first, because the user’s site ID (the one we have access to) is not the same as the user’s forum ID. CREATE PROCEDURE [dbo].[GetForumProfileDetails] ( @userId INT ) AS BEGIN SELECT Users.UserID, forumUsers.Twitter, forumUsers.Facebook, forumUsers.GooglePlus, forumUsers.LinkedIn, forumUsers.PublicEmailAddress FROM Users INNER JOIN Forum_Users forumUsers ON forumUsers.UserSiteID = Users.UserID WHERE Users.UserID = @userId END I’d like to make a shout out to Format SQL for its help with, well, formatting the above SQL!   The C# Class This is just the class representation of the results we expect to get from the stored procedure. NHibernate requires a virtual property for each column of data, and these properties must be called the same as the column headers. You will also need to ensure that there is a public or protected parameterless constructor. public class ForumProfile : IForumProfile { public virtual int UserID { get; set; } public virtual string Twitter { get; set; } public virtual string Facebook { get; set; } public virtual string GooglePlus { get; set; } public virtual string LinkedIn { get; set; } public virtual string PublicEmailAddress { get; set; } public ForumProfile() { } }   The NHibernate Mapping File This is the XML I wrote in order to make NHibernate a) aware of the stored procedure, and b) aware of the expected results of the procedure. <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="[namespace]" assembly="[assembly]"> <sql-query name="GetForumProfileDetails"> <return-scalar column="UserID" type="Int32"/> <return-scalar column="Twitter" type="String"/> <return-scalar column="Facebook" type="String"/> <return-scalar column="GooglePlus" type="String"/> <return-scalar column="LinkedIn" type="String"/> <return-scalar column="PublicEmailAddress" type="String"/> exec GetForumProfileDetails :UserID </sql-query> </hibernate-mapping>   Calling the Stored Procedure Finally, to bring it all together, the C# code that I used in order to execute the stored procedure! public IForumProfile GetForumUserProfile(IUser user) { return NHibernateHelper .GetCurrentSession() .GetNamedQuery("GetForumProfileDetails") .SetInt32("UserID", user.UserID) .SetResultTransformer( Transformers.AliasToBean(typeof (ForumProfile))) .UniqueResult<ForumProfile>(); } There are a number of ‘Set’ methods (i.e. SetInt32) that allow you specify values for any parameters in the procedure. The AliasToBean method is then required to map the returned scalars (as specified in the XML) to the correct C# class.

    Read the article

  • Easily Setup Fluent Nhibernate With Oracle

    Nowadays it is preferred to use ORM instead of old data access approaches. However, setting up an ORM like Fluent NHibernate with Oracle takes some time. With the help of NuGet you can setup such third party tools in no time. In this article I am going to to show how you can easily configure Fluent NHibernate with Oracle using NuGet. Moreover, the article will guide you in building a generic repository using Fluent NHibernate.

    Read the article

  • Deleting unreferenced child records with nhibernate

    - by Chev
    Hi There I am working on a mvc app using nhibernate as the orm (ncommon framework) I have parent/child entities: Product, Vendor & ProductVendors and a one to many relationship between them with Product having a ProductVendors collection Product.ProductVendors. I currently am retrieving a Product object and eager loading the children and sending these down the wire to my asp.net mvc client. A user will then modify the list of Vendors and post the updated Product back. I am using a custom model binder to generate the modified Product entity. I am able to update the Product fine and insert new ProductVendors. My problem is that dereferenced ProductVendors are not cascade deleted when specifying Product.ProductVendors.Clear() and calling _productRepository.Save(product). The problem seems to be with attaching the detached instance. Here are my mapping files: Product <?xml version="1.0" encoding="utf-8" ?> <id name="Id"> <generator class="guid.comb" /> </id> <version name="LastModified" unsaved-value="0" column="LastModified" /> <property name="Name" type="String" length="250" /> ProductVendors <?xml version="1.0" encoding="utf-8" ?> <id name="Id"> <generator class="guid.comb" /> </id> <version name="LastModified" unsaved-value="0" column="LastModified" /> <property name="Price" /> <many-to-one name="Product" class="Product" column="ProductId" lazy="false" not-null="true" /> <many-to-one name="Vendor" class="Vendor" column="VendorId" lazy="false" not-null="true" /> Custom Model Binder: using System; using Test.Web.Mvc; using Test.Domain; namespace Spoked.MVC { public class ProductUpdateModelBinder : DefaultModelBinder { private readonly ProductSystem ProductSystem; public ProductUpdateModelBinder(ProductSystem productSystem) { ProductSystem = productSystem; } protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { var product = bindingContext.Model as Product; if (product != null) { product.Category = ProductSystem.GetCategory(new Guid(bindingContext.ValueProvider["Category"].AttemptedValue)); product.Brand = ProductSystem.GetBrand(new Guid(bindingContext.ValueProvider["Brand"].AttemptedValue)); product.ProductVendors.Clear(); if (bindingContext.ValueProvider["ProductVendors"] != null) { string[] productVendorIds = bindingContext.ValueProvider["ProductVendors"].AttemptedValue.Split(','); foreach (string id in productVendorIds) { product.AddProductVendor(ProductSystem.GetVendor(new Guid(id)), 90m); } } } } } } Controller: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Update(Product product) { using (var scope = new UnitOfWorkScope()) { //product.ProductVendors.Clear(); _productRepository.Save(product); scope.Commit(); } using (new UnitOfWorkScope()) { IList<Vendor> availableVendors = _productSystem.GetAvailableVendors(product); productDetailEditViewModel = new ProductDetailEditViewModel(product, _categoryRepository.Select(x => x).ToList(), _brandRepository.Select(x => x).ToList(), availableVendors); } return RedirectToAction("Edit", "Products", new {id = product.Id.ToString()}); } The following test does pass though: [Test] [NUnit.Framework.Category("ProductTests")] public void Can_Delete_Product_Vendors_By_Dereferencing() { Product product; using(UnitOfWorkScope scope = new UnitOfWorkScope()) { Console.Out.WriteLine("Selecting..."); product = _productRepository.First(); Console.Out.WriteLine("Adding Product Vendor..."); product.AddProductVendor(_vendorRepository.First(), 0m); scope.Commit(); } Console.Out.WriteLine("About to delete Product Vendors..."); using (UnitOfWorkScope scope = new UnitOfWorkScope()) { Console.Out.WriteLine("Clearing Product Vendor..."); _productRepository.Save(product); // seems to be needed to attach entity to the persistance manager product.ProductVendors.Clear(); scope.Commit(); } } Going nuts here as I almost have a very nice solution between mvc, custom model binders and nhibernate. Just not seeing my deletes cascaded. Any help greatly appreciated. Chev

    Read the article

< Previous Page | 28 29 30 31 32 33 34 35 36 37 38 39  | Next Page >