Search Results

Search found 2353 results on 95 pages for 'nhibernate validator'.

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

  • Fluent NHibernate - How to map the foreign key column as a property

    - by Steve
    I am sure this is a straightforward question but consider the following: I have a reference between company and sector as follows: public class Company { public Guid ID { get; set; } public Sector Sector { get; set; } public Guid SectorID { get; set; } } public class Sector { public Guid ID { get; set; } public string Name { get; set; } } Ok. What I want is the SectorID of the Company object to be populated after I go: (new Company()).Sector = new Sector() { Name="asdf" } and do a flush. The mapping I am using kindly creates an additional column in the database called Sector_Id in the Company table, but this is not available as a property on Company. I want the SectorID property to be filled. The mapping i am currently using in the CompanyMap is References(c = c.Sector).Cascade.All(); Does anyone have any ideas?

    Read the article

  • NHibernate Linq Provider question

    - by csizo
    Can anyone answer me what are the differences of Session.Query Session.Linq and Session.QueryOver What I'm really interested in: What would be supported in the future versions. What should I start to use in a clean project. Please tell me your thoughts about these three... Thanks, Zoltán

    Read the article

  • How to access the backing field of an inherited class using fluent nhibernate

    - by Akk
    How do i set the Access Strategy in the mapping class to point to the inherited _photos field? public class Content { private IList<Photo> _photos; public Content() { _photos = new List<Photo>(); } public virtual IEnumerable<Photo> Photos { get { return _photos; } } public virtual void AddPhoto() {...} } public class Article : Content { public string Body {get; set;} } I am currently using thw following to try and locate the backing field but an exception is thrown as it cannot be found. public class ArticleMap : ClassMap<Article> { HasManyToMany(x => x.Photos) .Access.CamelCaseField(Prefix.Underscore) //_photos //... } i tried moving the backing field _photos directly into the class and the access works. So how can i access the backing field of an inherited class?

    Read the article

  • Mapping One-to-One subclass in Fluent NHibernate

    - by Mike C.
    I have the following database structure: Event table Id - Guid (PK) Name - NVarChar Description - NVarChar SpecialEvent table Id - Guid (PK) StartDate - DateTime EndDate - DateTime I have an abstract Event class, and a SpecialEvent class that inherits from it. Eventually I will have a RecurringEvent class which will inherit from the Event class also. I'd like to map the SpecialEvent class while preserving a one-to-one relationship mapped with the Ids, if possible. Can anybody point me in the correct direction? Thanks!

    Read the article

  • NHibernate: discriminator without common base class?

    - by joniba
    Is it possible to map two classes to the same property without them sharing a common base class? For example, a situation like this: class Rule { public virtual int SequenceNumber { get; set; } public virtual ICondition Condition { get; set; } } interface ICondition { } class ExpressionCondition : ICondition { public virtual string Expression { get; set; } } class ThresholdCondition : ICondition { public virtual int Threshold { get; set; } } I also cannot add some empty abstract class that both conditions inherit from because the two ICondition implementations exist in different domains that are not allowed to reference each other. (Please no responses telling me that this situation should not occur in the first place - I'm aware of it and it doesn't help me.)

    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

  • mapping 'value object' collection in (Fluent) NHibernate

    - by adrin
    I have the following entity public class Employee { public virtual int Id {get;set;} public virtual ISet<Hour> XboxBreakHours{get;set} public virtual ISet<Hour> CoffeeBreakHours {get;set} } public class Hour { public DateTime Time {get;set;} } (What I want to do here is store information that employee A plays Xbox everyday let's say at 9:00 13:30 and has a coffee break everyday at 7:00 12:30 18:00) - I am not sure if my approach is valid at all here. The question is how should my (ideally fluent) mappings look like here? It is not necessary (from my point of view) for Hour class to have Id or be accessible from some kind of repository.

    Read the article

  • How to get number of delete using NHibernate IStatistics

    - by epitka
    I am trying to get the number of delete statements issued during the session, so I enabled statistics generation and I got a reference to it through SessionFactory.Statistics. But I don't see a way to get the global number of deletes. I can get the statistics for the entity, but I have one many-to-many mapped relationship that does not materialize in an entity, everything is done through a table that is not mapped to an entity. Is there a way to get this number?

    Read the article

  • NHibernate: Dynamically swapping a single domain model between multiple physical data models

    - by Nigel
    Hi In this article Ayende describes how to map a single domain model to multiple physical data models. Is it possible to extend this principle such that the mapping can chosen dynamically? So for example, imagine we had an entity that could be written to the same physical schema in three ways depending on its current status, and lets assume that regardless of status each entity had a unique identifier. One solution would be to represent the entity in its different states with three separate classes: one for each mapping. Then the entity could be loaded and in order to change its state the entity could be mapped to a class representing one of its other states and then saved back to the schema, making use of a different mapping. I was wondering if it is at all possible to have the same entity represented by one class that held a status flag (kind of like a discriminator), and any save to the schema would choose the appropriate mapping based on the value of the status flag. Hopefully that made sense! Many thanks.

    Read the article

  • NHibernate Mapping + Iset

    - by jack
    Hi all I have a mapping file <set name="Friends" table="Friends"> <key column="UserId"/> <many-to-many class="User" column="FriendId"/> </set> I would like to specify extra columns for the friend table this creates. For example Approve (the user must approve the friend request) Is there a easy way?

    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 Pitfalls: Loading Foreign Key Properties

    - by Ricardo Peres
    This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. When saving a new entity that has references to other entities (one to one, many to one), one has two options for setting their values: Load each of these references by calling ISession.Get and passing the foreign key; Load a proxy instead, by calling ISession.Load with the foreign key. So, what is the difference? Well, ISession.Get goes to the database and tries to retrieve the record with the given key, returning null if no record is found. ISession.Load, on the other hand, just returns a proxy to that record, without going to the database. This turns out to be a better option, because we really don’t need to retrieve the record – and all of its non-lazy properties and collections -, we just need its key. An example: 1: //going to the database 2: OrderDetail od = new OrderDetail(); 3: od.Product = session.Get<Product>(1); //a product is retrieved from the database 4: od.Order = session.Get<Order>(2); //an order is retrieved from the database 5:  6: session.Save(od); 7:  8: //creating in-memory proxies 9: OrderDetail od = new OrderDetail(); 10: od.Product = session.Load<Product>(1); //a proxy to a product is created 11: od.Order = session.Load<Order>(2); //a proxy to an order is created 12:  13: session.Save(od); So, if you just need to set a foreign key, use ISession.Load instead of ISession.Get.

    Read the article

  • Run your own XHTML validator

    - by TATWORTH
    Whilst the W3C do provide an excellent service for manually checking your web pages, there are times when an alternative is required. There is for example a web service at http://validator.w3.org/docs/api.html  This can be for programmatically checking your pages (provided you make no more than 1 call per second). The W3C do provide all the source code needed to run your own validation service. Get the full details at: ·         Installation and development information for the W3C Markup Validator   http://validator.w3.org/docs/devel.html ·         Source Availability http://validator.w3.org/source/

    Read the article

  • nhibernate sql Express connection issue - error: 26 - Error Locating Server/Instance Specified

    - by frosty
    I can connect fine with normal ado.net. However i get the following error when i tried to connect nHibernate. hibernate.cfg.xml <?xml version="1.0" encoding="utf-8" ?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> <property name="connection.connection_string">Server=xxxxx\SQLEXPRESS; Database=xxxxx; User ID=xxxxx; Password=xxxxx; Trusted_Connection=True</property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property> <property name="show_sql">true</property> </session-factory> </hibernate-configuration> Server error A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Full stack [SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4845255 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194 System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +4858557 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +342 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +221 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +185 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +433 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117 System.Data.SqlClient.SqlConnection.Open() +122 NHibernate.Connection.DriverConnectionProvider.GetConnection() +102 NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare() +15 NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect dialect, IConnectionHelper connectionHelper) +65 NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactory sessionFactory) +80 NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners) +599 NHibernate.Cfg.Configuration.BuildSessionFactory() +87 XXX.Domain.Repositories.NHibernateHelper.get_SessionFactory() in D:\dev\MyProject\XXX\XXX.Domain\Repositories\NHibernateHelper.cs:23 XXX.Domain.Repositories.NHibernateHelper.OpenSession() in D:\dev\MyProject\XXX\XXX.Domain\Repositories\NHibernateHelper.cs:31 XXX.Domain.Repositories.EntryRepository.GetCountByGmapId(Int32 gmapId) in D:\dev\MyProject\XXX\XXX.Domain\Repositories\EntryRepository.cs:152 XXX.Controls.Activity.BindRepeater(Int32 id) in D:\dev\MyProject\XXX\XXX.Controls\Activity.ascx.cs:58 XXX.Controls.Activity.DropDownListMaps_SelectedIndexChanged(Object sender, EventArgs e) in D:\dev\MyProject\XXX\XXX.Controls\Activity.ascx.cs:75 System.Web.UI.WebControls.ListControl.OnSelectedIndexChanged(EventArgs e) +111 System.Web.UI.WebControls.DropDownList.RaisePostDataChangedEvent() +134 System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() +10 System.Web.UI.Page.RaiseChangedEvents() +165 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1485

    Read the article

  • Using Unit of Work design pattern / NHibernate Sessions in an MVVM WPF

    - by Echiban
    I think I am stuck in the paralysis of analysis. Please help! I currently have a project that Uses NHibernate on SQLite Implements Repository and Unit of Work pattern: http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/04/10/nhibernate-and-the-unit-of-work-pattern.aspx MVVM strategy in a WPF app Unit of Work implementation in my case supports one NHibernate session at a time. I thought at the time that this makes sense; it hides inner workings of NHibernate session from ViewModel. Now, according to Oren Eini (Ayende): http://msdn.microsoft.com/en-us/magazine/ee819139.aspx He convinces the audience that NHibernate sessions should be created / disposed when the view associated with the presenter / viewmodel is disposed. He presents issues why you don't want one session per windows app, nor do you want a session to be created / disposed per transaction. This unfortunately poses a problem because my UI can easily have 10+ view/viewmodels present in an app. He is presenting using a MVP strategy, but does his advice translate to MVVM? Does this mean that I should scrap the unit of work and have viewmodel create NHibernate sessions directly? Should a WPF app only have one working session at a time? If that is true, when should I create / dispose a NHibernate session? And I still haven't considered how NHibernate Stateless sessions fit into all this! My brain is going to explode. Please help!

    Read the article

  • NHibernate.Bytecode.UnableToLoadProxyFactoryFactoryException

    - by Shane
    I have the following code set up in my Startup IDictionary properties = new Dictionary(); properties.Add("connection.driver_class", "NHibernate.Driver.SqlClientDriver"); properties.Add("dialect", "NHibernate.Dialect.MsSql2005Dialect"); properties.Add("proxyfactory.factory_class", "NNHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"); properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider"); properties.Add("connection.connection_string", "Data Source=ZEUS;Initial Catalog=mydb;Persist Security Info=True;User ID=sa;Password=xxxxxxxx"); InPlaceConfigurationSource source = new InPlaceConfigurationSource(); source.Add(typeof(ActiveRecordBase), (IDictionary<string, string>) properties); Assembly asm = Assembly.Load("Repository"); Castle.ActiveRecord.ActiveRecordStarter.Initialize(asm, source); I am getting the following error: failed: NHibernate.Bytecode.UnableToLoadProxyFactoryFactoryException : Unable to load type 'NNHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle' during configuration of proxy factory class. Possible causes are: - The NHibernate.Bytecode provider assembly was not deployed. - The typeName used to initialize the 'proxyfactory.factory_class' property of the session-factory section is not well formed. I have read and read I am referecning the All the assemblies listed and I am at a total loss as what to try next. Castle.ActiveRecord.dll Castle.DynamicProxy2.dll Iesi.Collections.dll log4net.dll NHibernate.dll NHibernate.ByteCode.Castle.dll I am 100% sure the assembly is in the bin. Anyone have any ideas?

    Read the article

  • Moving from NHibernate to FluentNHibernate: assembly error (related to versions)?

    - by goober
    Not sure where to start, but I had gotten the most recent version of NHibernate, successfully mapped the most simple of business objects, etc. When trying to move to FluentNHibernate and do the same thing, I got this error message on build: "System.IO.FileLoadException: Could not load file or assembly 'NHibernate, Version=2.1.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference." Background: I'm new to Hibernate, NHibernate, and FluentNHibernate -- but not to .NET, C#, etc. Database I have a database table called Category: (PK) CategoryID (type: int), unique, auto-incrementing UserID (type: uniqueidentifier) -- given the value of the user Guid in ASP.NET database Title (type: varchar(50) -- the title of the category Components involved: I have a SessionProviderClass which creates the mapping to the database I have a Category class which has all the virtual methods for FluentNHibernate to override I have a CategoryMap : ClassMap class, which does the fluent mappings for the entity I have a CategoryRepository class that contains the method to add & save the category I have the TestCatAdd.aspx file which uses the CategoryRepository class. Would be happy to post code for any of those, but I'm not sure that it's necessary, as I think the issue is that somewhere there's a version conflict between what FluentNHibernate references and the NHibernate I have installed from before. Thanks in advance for any help you can give!

    Read the article

  • How to find unmapped properties in a NHibernate mapped class?

    - by haarrrgh
    I just had a NHibernate related problem where I forgot to map one property of a class. A very simplified example: public class MyClass { public virtual int ID { get; set; } public virtual string SomeText { get; set; } public virtual int SomeNumber { get; set; } } ...and the mapping file: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyAssembly" namespace="MyAssembly.MyNamespace"> <class name="MyClass" table="SomeTable"> <property name="ID" /> <property name="SomeText" /> </class> </hibernate-mapping> In this simple example, you can see the problem at once: there is a property named "SomeNumber" in the class, but not in the mapping file. So NHibernate will not map it and it will always be zero. The real class had a lot more properties, so the problem was not as easy to see and it took me quite some time to figure out why SomeNumber always returned zero even though I was 100% sure that the value in the database was != zero. So, here is my question: Is there some simple way to find this out via NHibernate? Like a compiler warning when a class is mapped, but some of its properties are not. Or some query that I can run that shows me unmapped properties in mapped classes...you get the idea. (Plus, it would be nice if I could exclude some legacy columns that I really don't want mapped.)

    Read the article

  • Internal compiler error: Could not load type NHibernate.Cfg.Configuration

    - by Simon
    I'm referencing the NHibernate dll version 2.1.2-GA, and am unable to compile under Mono 2.8.1. I've tried using NHibernate 3 instead and it compiles fine. A simple example of the code that's failing is NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration(); and the error is Error CS0584: Internal compiler error: Could not load type 'NHibernate.Cfg.Configuration' from assembly 'NHibernate, Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4'. (CS0584) As mentioned it compiles with no problems using NHibernate 3, does anyone have any ideas how to get it working with NHiberate 2.1.2?

    Read the article

  • How to get interpolated message in NHibernate.Validator

    - by SztupY
    Hi! I'm trying to integrate NHibernate.Validator with ASP.NET MVC client side validations, and the only problem I found is that I simply can't convert the non-interpolated message to a human-readable one. I thought this would be an easy task, but turned out to be the hardest part of the client-side validation. The main problem is that because it's not server-side, I actually only need the validation attributes that are being used, and I don't actually have an instance or anything else at hand. Here are some excerpts from what I've been already trying: // Get the the default Message Interpolator from the Engine IMessageInterpolator interp = _engine.Interpolator; if (interp == null) { // It is null?? Oh, try to create a new one interp = new NHibernate.Validator.Interpolator.DefaultMessageInterpolator(); } // We need an instance of the object that needs to be validated, se we have to create one object instance = Activator.CreateInstance(Metadata.ContainerType); // we enumerate all attributes of the property. For example we have found a PatternAttribute var a = attr as PatternAttribute; // it seems that the default message interpolator doesn't work, unless initialized if (interp is NHibernate.Validator.Interpolator.DefaultMessageInterpolator) { (interp as NHibernate.Validator.Interpolator.DefaultMessageInterpolator).Initialize(a); } // but even after it is initialized the following will throw a NullReferenceException, although all of the parameters are specified, and they are not null (except for the properties of the instance, which are all null, but this can't be changed) var message = interp.Interpolate(new InterpolationInfo(Metadata.ContainerType, instance, PropertyName, a, interp, a.Message)); I know that the above is a fairly complex code for a seemingly simple question, but I'm still stuck without solution. Is there any way to get the interpolated string out of NHValidator?

    Read the article

  • How to use Nhibernate Validator + NHib component + ddl

    - by mynkow
    I just configured my NHibValidator. My NHibernate creates the DB schema. When I set MaxLenght="20" to some property of a class then in the database the length appears in the database column. I am doing this in the NHibValidator xml file. But the problem is that I have components and cannot figure out how to achieve this behaviour. The component is configured correctly in the Customer.hbm.xml file. EDIT: Well, I found that Hibernate Validator users had the same problem two years ago. http://opensource.atlassian.com/projects/hibernate/browse/HV-25 Is this an issue for NHibernate Validator or it is fixed. If it is working tell me how please. ----------------------------------------------------- public class Customer { public virtual string Name{get;set;} public virtual Contact Contacts{ get; } } ----------------------------------------------------- public class Contact { public virtual string Address{get;set;} } ----------------------------------------------------- <?xml version="1.0" encoding="utf-8" ?> <nhv-mapping xmlns="urn:nhibernate-validator-1.0" namespace="MyNamespace" assembly="MyAssembly"> <class name="Customer"> <property name="Name"> <length max="20"/> </property> <property name="Contacts"> <notNull/> <valid/> </property> </class> </nhv-mapping> ----------------------------------------------------- <?xml version="1.0" encoding="utf-8" ?> <nhv-mapping xmlns="urn:nhibernate-validator-1.0" namespace="MyNamespace" assembly="MyAssembly"> <class name="Contact"> <property name="Address"> <length max="50"/> <valid/> </property> </class> </nhv-mapping> -----------------------------------------------------

    Read the article

  • Caching NHibernate Named Queries

    - by TStewartDev
    I recently started a new job and one of my first tasks was to implement a "popular products" design. The parameters were that it be done with NHibernate and be cached for 24 hours at a time because the query will be pretty taxing and the results do not need to be constantly up to date. This ended up being tougher than it sounds. The database schema meant a minimum of four joins with filtering and ordering criteria. I decided to use a stored procedure rather than letting NHibernate create the SQL for me. Here is a summary of what I learned (even if I didn't ultimately use all of it): You can't, at the time of this writing, use Fluent NHibernate to configure SQL named queries or imports You can return persistent entities from a stored procedure and there are a couple ways to do that You can populate POCOs using the results of a stored procedure, but it isn't quite as obvious You can reuse your named query result mapping other places (avoid duplication) Caching your query results is not at all obvious Testing to see if your cache is working is a pain NHibernate does a lot of things right. Having unified, up-to-date, comprehensive, and easy-to-find documentation is not one of them. By the way, if you're new to this, I'll use the terms "named query" and "stored procedure" (from NHibernate's perspective) fairly interchangeably. Technically, a named query can execute any SQL, not just a stored procedure, and a stored procedure doesn't have to be executed from a named query, but for reusability, it seems to me like the best practice. If you're here, chances are good you're looking for answers to a similar problem. You don't want to read about the path, you just want the result. So, here's how to get this thing going. The Stored Procedure NHibernate has some guidelines when using stored procedures. For Microsoft SQL Server, you have to return a result set. The scalar value that the stored procedure returns is ignored as are any result sets after the first. Other than that, it's nothing special. CREATE PROCEDURE GetPopularProducts @StartDate DATETIME, @MaxResults INT AS BEGIN SELECT [ProductId], [ProductName], [ImageUrl] FROM SomeTableWithJoinsEtc END The Result Class - PopularProduct You have two options to transport your query results to your view (or wherever is the final destination): you can populate an existing mapped entity class in your model, or you can create a new entity class. If you go with the existing model, the advantage is that the query will act as a loader and you'll get full proxied access to the domain model. However, this can be a disadvantage if you require access to the related entities that aren't loaded by your results. For example, my PopularProduct has image references. Unless I tie them into the query (thus making it even more complicated and expensive to run), they'll have to be loaded on access, requiring more trips to the database. Since we're trying to avoid trips to the database by using a second-level cache, we should use the second option, which is to create a separate entity for results. This approach is (I believe) in the spirit of the Command-Query Separation principle, and it allows us to flatten our data and optimize our report-generation process from data source to view. public class PopularProduct { public virtual int ProductId { get; set; } public virtual string ProductName { get; set; } public virtual string ImageUrl { get; set; } } The NHibernate Mappings (hbm) Next up, we need to let NHibernate know about the query and where the results will go. Below is the markup for the PopularProduct class. Notice that I'm using the <resultset> element and that it has a name attribute. The name allows us to drop this into our query map and any others, giving us reusability. Also notice the <import> element which lets NHibernate know about our entity class. <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <import class="PopularProduct, Infrastructure.NHibernate, Version=1.0.0.0"/> <resultset name="PopularProductResultSet"> <return-scalar column="ProductId" type="System.Int32"/> <return-scalar column="ProductName" type="System.String"/> <return-scalar column="ImageUrl" type="System.String"/> </resultset> </hibernate-mapping>  And now the PopularProductsMap: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <sql-query name="GetPopularProducts" resultset-ref="PopularProductResultSet" cacheable="true" cache-mode="normal"> <query-param name="StartDate" type="System.DateTime" /> <query-param name="MaxResults" type="System.Int32" /> exec GetPopularProducts @StartDate = :StartDate, @MaxResults = :MaxResults </sql-query> </hibernate-mapping>  The two most important things to notice here are the resultset-ref attribute, which links in our resultset mapping, and the cacheable attribute. The Query Class – PopularProductsQuery So far, this has been fairly obvious if you're familiar with NHibernate. This next part, maybe not so much. You can implement your query however you want to; for me, I wanted a self-encapsulated Query class, so here's what it looks like: public class PopularProductsQuery : IPopularProductsQuery { private static readonly IResultTransformer ResultTransformer; private readonly ISessionBuilder _sessionBuilder;   static PopularProductsQuery() { ResultTransformer = Transformers.AliasToBean<PopularProduct>(); }   public PopularProductsQuery(ISessionBuilder sessionBuilder) { _sessionBuilder = sessionBuilder; }   public IList<PopularProduct> GetPopularProducts(DateTime startDate, int maxResults) { var session = _sessionBuilder.GetSession(); var popularProducts = session .GetNamedQuery("GetPopularProducts") .SetCacheable(true) .SetCacheRegion("PopularProductsCacheRegion") .SetCacheMode(CacheMode.Normal) .SetReadOnly(true) .SetResultTransformer(ResultTransformer) .SetParameter("StartDate", startDate.Date) .SetParameter("MaxResults", maxResults) .List<PopularProduct>();   return popularProducts; } }  Okay, so let's look at each line of the query execution. The first, GetNamedQuery, matches up with our NHibernate mapping for the sql-query. Next, we set it as cacheable (this is probably redundant since our mapping also specified it, but it can't hurt, right?). Then we set the cache region which we'll get to in the next section. Set the cache mode (optional, I believe), and my cache is read-only, so I set that as well. The result transformer is very important. This tells NHibernate how to transform your query results into a non-persistent entity. You can see I've defined ResultTransformer in the static constructor using the AliasToBean transformer. The name is obviously leftover from Java/Hibernate. Finally, set your parameters and then call a result method which will execute the query. Because this is set to cached, you execute this statement every time you run the query and NHibernate will know based on your parameters whether to use its cached version or a fresh version. The Configuration – hibernate.cfg.xml and Web.config You need to explicitly enable second-level caching in your hibernate configuration: <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> [...] <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property> <property name="cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider,NHibernate.Caches.SysCache</property> <property name="cache.use_query_cache">true</property> <property name="cache.use_second_level_cache">true</property> [...] </session-factory> </hibernate-configuration> Both properties "use_query_cache" and "use_second_level_cache" are necessary. As this is for a web deployement, we're using SysCache which relies on ASP.NET's caching. Be aware of this if you're not deploying to the web! You'll have to use a different cache provider. We also need to tell our cache provider (in this cache, SysCache) about our caching region: <syscache> <cache region="PopularProductsCacheRegion" expiration="86400" priority="5" /> </syscache> Here I've set the cache to be valid for 24 hours. This XML snippet goes in your Web.config (or in a separate file referenced by Web.config, which helps keep things tidy). The Payoff That should be it! At this point, your queries should run once against the database for a given set of parameters and then use the cache thereafter until it expires. You can, of course, adjust settings to work in your particular environment. Testing Testing your application to ensure it is using the cache is a pain, but if you're like me, you want to know that it's actually working. It's a bit involved, though, so I'll create a separate post for it if comments indicate there is interest.

    Read the article

  • Speeding Up NHibernate Startup Time

    - by Ricardo Peres
    One technique I use and posted on the NHUsers mailing list consists in serializing a previously-configured Configuration to the filesystem and deserializing it on all subsequente starts of the application: Configuration cfg = null; IFormatter serializer = new BinaryFormatter(); //first time cfg = new Configuration().Configure(); using (Stream stream = File.OpenWrite("Configuration.serialized")) { serializer.Serialize(stream, configuration); } //other times using (Stream stream = File.OpenRead("Configuration.serialized")) { cfg = serializer.Deserialize(stream) as Configuration; } Check it out for yourselves. SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • NHibernate mapping many to many three tables [closed]

    - by Tony
    I am trying to get this solved but can't so far. all kind of errors. These are my db tables Person (personID, name, age) Role (roleID, roleName) PersonRoles(personRolesID, personID, roleID) this is my domain class public Person { public virtual Roles RolesForThisPerson {get;set;} public virtual string Name {get;set;} public virtual int Age {get;set;} } public Roles { public virtual IList<string> RoleList {get;set;} } I am totally lost on how to approach this. I am so confused about sets, bags, lists... i don't even know where to start. Anybody can give me a little push here? thanks

    Read the article

  • How to add new object to an IList mapped as a one-to-many with NHibernate?

    - by Jørn Schou-Rode
    My model contains a class Section which has an ordered list of Statics that are part of this section. Leaving all the other properties out, the implementation of the model looks like this: public class Section { public virtual int Id { get; private set; } public virtual IList<Static> Statics { get; private set; } } public class Static { public virtual int Id { get; private set; } } In the database, the relationship is implemented as a one-to-many, where the table Static has a foreign key pointing to Section and an integer column Position to store its index position in the list it is part of. The mapping is done in Fluent NHibernate like this: public SectionMap() { Id(x => x.Id); HasMany(x => x.Statics).Cascade.All().LazyLoad() .AsList(x => x.WithColumn("Position")); } public StaticMap() { Id(x => x.Id); References(x => x.Section); } Now I am able to load existing Statics, and I am also able to update the details of those. However, I cannot seem to find a way to add new Statics to a Section, and have this change persisted to the database. I have tried several combinations of: mySection.Statics.Add(myStatic) session.Update(mySection) session.Save(myStatic) but the closest I have gotten (using the first two statements), is to an SQL exception reading: "Cannot insert the value NULL into column 'Position'". Clearly an INSERT is attempted here, but NHibernate does not seem to automatically append the index position to the SQL statement. What am I doing wrong? Am I missing something in my mappings? Do I need to expose the Position column as a property and assign a value to it myself? EDIT: Apparently everything works as expected, if I remove the NOT NULL constraint on the Static.Position column in the database. I guess NHibernate makes the insert and immediatly after updates the row with a Position value. While this is an anwers to the question, I am not sure if it is the best one. I would prefer the Position column to be not nullable, so I still hope there is some way to make NHibernate provide a value for that column directly in the INSERT statement. Thus, the question is still open. Any other solutions?

    Read the article

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