Search Results

Search found 1672 results on 67 pages for 'nhibernate'.

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

  • 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 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

  • 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

  • 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

  • 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 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

  • 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

  • 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

  • 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

  • NHibernate AssertException: Interceptor.OnPrepareStatement(SqlString) returned null or empty SqlString.

    - by jwynveen
    I am trying to switch a table from being a many-to-one mapping to being many-to-many with an intermediate mapping table. However, when I switched it over and tried to do a query on it with NHibernate, it's giving me this error: "Interceptor.OnPrepareStatement(SqlString) returned null or empty SqlString." My query was originally something more complex, but I switched it to a basic fetch all and I'm still having the problem: Session.QueryOver<T>().Future(); It would seem to either be a problem in my model mapping files or something in my database. Here are my model mappings: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="GBI.Core" namespace="GBI.Core.Models"> <class name="Market" table="gbi_Market"> <id name="Id" column="MarketId"> <generator class="identity" /> </id> <property name="Name" /> <property name="Url" /> <property name="Description" type="StringClob" /> <property name="Rating" /> <property name="RatingComment" /> <property name="RatingCommentedOn" /> <many-to-one name="RatingCommentedBy" column="RatingCommentedBy" lazy="proxy"></many-to-one> <property name="ImageFilename" /> <property name="CreatedOn" /> <property name="ModifiedOn" /> <property name="IsDeleted" /> <many-to-one name="CreatedBy" column="CreatedBy" lazy="proxy"></many-to-one> <many-to-one name="ModifiedBy" column="ModifiedBy" lazy="proxy"></many-to-one> <set name="Content" where="IsDeleted=0 and ParentContentId is NULL" order-by="Ordering asc, CreatedOn asc, Name asc" lazy="extra"> <key column="MarketId" /> <one-to-many class="MarketContent" /> </set> <set name="FastFacts" where="IsDeleted=0" order-by="Ordering asc, CreatedOn asc, Name asc" lazy="extra"> <key column="MarketId" /> <one-to-many class="MarketFastFact" /> </set> <set name="NewsItems" table="gbi_NewsItem_Market_Map" lazy="true"> <key column="MarketId" /> <many-to-many class="NewsItem" fetch="join" column="NewsItemId" where="IsDeleted=0"/> </set> <!--<set name="MarketUpdates" table="gbi_Market_MarketUpdate_Map" lazy="extra"> <key column="MarketId" /> <many-to-many class="MarketUpdate" fetch="join" column="MarketUpdateId" where="IsDeleted=0" order-by="CreatedOn desc" /> </set>--> <set name="Documents" table="gbi_Market_Document_Map" lazy="true"> <key column="MarketId" /> <many-to-many class="Document" fetch="join" column="DocumentId" where="IsDeleted=0"/> </set> </class> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="GBI.Core" namespace="GBI.Core.Models"> <class name="MarketUpdate" table="gbi_MarketUpdate"> <id name="Id" column="MarketUpdateId"> <generator class="identity" /> </id> <property name="Description" /> <property name="CreatedOn" /> <property name="ModifiedOn" /> <property name="IsDeleted" /> <!--<many-to-one name="Market" column="MarketId" lazy="proxy"></many-to-one>--> <set name="Comments" where="IsDeleted=0" order-by="CreatedOn desc" lazy="extra"> <key column="MarketUpdateId" /> <one-to-many class="MarketUpdateComment" /> </set> <many-to-one name="CreatedBy" column="CreatedBy" lazy="proxy"></many-to-one> <many-to-one name="ModifiedBy" column="ModifiedBy" lazy="proxy"></many-to-one> </class> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="GBI.Core" namespace="GBI.Core.Models"> <class name="MarketUpdateMarketMap" table="gbi_Market_MarketUpdate_Map"> <id name="Id" column="MarketUpdateMarketMapId"> <generator class="identity" /> </id> <property name="CreatedOn" /> <property name="ModifiedOn" /> <property name="IsDeleted" /> <many-to-one name="CreatedBy" column="CreatedBy" lazy="proxy"></many-to-one> <many-to-one name="ModifiedBy" column="ModifiedBy" lazy="proxy"></many-to-one> <many-to-one name="MarketUpdate" column="MarketUpdateId" lazy="proxy"></many-to-one> <many-to-one name="Market" column="MarketId" lazy="proxy"></many-to-one> </class> As I mentioned, MarketUpdate was originally a many-to-one with Market (MarketId column is still in there, but I'm ignoring it. Could this be a problem?). But I've added in the Market_MarketUpdate_Map table to make it a many-to-many. I'm running in circles trying to figure out what this could be. I couldn't find any reference to this error when searching. And it doesn't provide much detail. Using: NHibernate 2.2 .NET 4.0 SQL Server 2005

    Read the article

  • How implement the Open Session in View pattern in NHibernate?

    - by MCardinale
    I'm using ASP.NET MVC + NHibernate + Fluent NHibernate and having a problem with lazy loading. Through this question (http://stackoverflow.com/questions/2519964/how-to-fix-a-nhibernate-lazy-loading-error-no-session-or-session-was-closed), I've discovered that I have to implement the Open Session in View pattern , but I don't know how. In my repositories classes, I use methods like this public ImageGallery GetById(int id) { using(ISession session = NHibernateSessionFactory.OpenSession()) { return session.Get<ImageGallery>(id); } } public void Add(ImageGallery imageGallery) { using(ISession session = NHibernateSessionFactory.OpenSession()) { using(ITransaction transaction = session.BeginTransaction()) { session.Save(imageGallery); transaction.Commit(); } } } And this is my Session Factory helper class: public class NHibernateSessionFactory { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if(_sessionFactory == null) { _sessionFactory = Fluently.Configure() .Database(MySQLConfiguration.Standard.ConnectionString(MyConnString)) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ImageGalleryMap>()) .ExposeConfiguration(c => c.Properties.Add("hbm2ddl.keywords", "none")) .BuildSessionFactory(); } return _sessionFactory; } } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } Someone could help me to implements Open Session in View pattern? Thank you.

    Read the article

  • How to configure SQLite to run with NHibernate where assembly resolves System.Data.SQLite?

    - by Michael Hedgpeth
    I am using the latest NHibernate 2.1.0Beta2. I'm trying to unit test with SQLite and have the configuration set up as: Dictionary<string, string> properties = new Dictionary<string, string>(); properties.Add("connection.driver_class", "NHibernate.Driver.SQLite20Driver"); properties.Add("dialect", "NHibernate.Dialect.SQLiteDialect"); properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider"); properties.Add("query.substitutions", "true=1;false=0"); properties.Add("connection.connection_string", "Data Source=test.db;Version=3;New=True;"); properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu"); configuration = new Configuration(); configuration.SetProperties(properties); When I try to run it, I get the following error: NHibernate.HibernateException: The IDbCommand and IDbConnection implementation in the assembly System.Data.SQLite could not be found. Ensure that the assembly System.Data.SQLite is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use <qualifyAssembly/> element in the application configuration file to specify the full name of the assembly. at NHibernate.Driver.ReflectionBasedDriver..ctor(String driverAssemblyName, String connectionTypeName, String commandTypeName) in c:\CSharp\NH\nhibernate\src\NHibernate\Driver\ReflectionBasedDriver.cs: line 26 at NHibernate.Driver.SQLite20Driver..ctor() in c:\CSharp\NH\nhibernate\src\NHibernate\Driver\SQLite20Driver.cs: line 28 So it looks like I need to reference the assembly directly. How would I do this so I don't get this error anymore? I downloaded the latest assembly from here: http://sourceforge.net/projects/sqlite-dotnet2.

    Read the article

  • Serialized NHibernate Configuration objects - detect out of date or rebuild on demand?

    - by fostandy
    I've been using serialized nhibernate configuration objects (also discussed here and here) to speed up my application startup from about 8s to 1s. I also use fluent-nhibernate, so the path is more like ClassMap class definitions in code fluentconfiguration xml nhibernate configuration configuration serialized to disk. The problem from doing this is that one runs the risk of out of date mappings - if I change the mappings but forget to rebuild the serialized configuration, then I end up using the old mappings without realising it. This does not always result in an immediate and obvious error during testing, and several times the misbehaviour has been a real pain to detect and fix. Does anybody have any idea how I would be able to detect if my classmaps have changed, so that I could either issue an immediate warning/error or rebuild it on demand? At the moment I am comparing timestamps on my compiled assembly against the serialized configuration. This will pickup mapping changes, but unfortunately it generates a massive false positive rate as ANY change to the code results in an out of date flag. I can't move the classmaps to another assembly as they are tightly integrated into the business logic. This has been niggling me for a while so I was wondering if anybody had any suggestions?

    Read the article

  • How do you automap List<float> or float[] with Fluent NHibernate?

    - by Tom Bushell
    Having successfully gotten a sample program working, I'm now starting to do Real Work with Fluent NHibernate - trying to use Automapping on my project's class heirarchy. It's a scientific instrumentation application, and the classes I'm mapping have several properties that are arrays of floats e.g. private float[] _rawY; public virtual float[] RawY { get { return _rawY; } set { _rawY = value; } } These arrays can contain a maximum of 500 values. I didn't expect Automapping to work on arrays, but tried it anyway, with some success at first. Each array was auto mapped to a BLOB (using SQLite), which seemed like a viable solution. The first problem came when I tried to call SaveOrUpdate on the objects containing the arrays - I got "No persister for float[]" exceptions. So my next thought was to convert all my arrays into ILists e.g. public virtual IList<float> RawY { get; set; } But now I get: NHibernate.MappingException: Association references unmapped class: System.Single Since Automapping can deal with lists of complex objects, it never occured to me it would not be able to map lists of basic types. But after doing some Googling for a solution, this seems to be the case. Some people seem to have solved the problem, but the sample code I saw requires more knowledge of NHibernate than I have right now - I didn't understand it. Questions: 1. How can I make this work with Automapping? 2. Also, is it better to use arrays or lists for this application? I can modify my app to use either if necessary (though I prefer lists). Edit: I've studied the code in Mapping Collection of Strings, and I see there is test code in the source that sets up an IList of strings, e.g. public virtual IList<string> ListOfSimpleChildren { get; set; } [Test] public void CanSetAsElement() { new MappingTester<OneToManyTarget>() .ForMapping(m => m.HasMany(x => x.ListOfSimpleChildren).Element("columnName")) .Element("class/bag/element").Exists(); } so this must be possible using pure Automapping, but I've had zero luck getting anything to work, probably because I don't have the requisite knowlege of manually mapping with NHibernate. Starting to think I'm going to have to hack this (by encoding the array of floats as a single string, or creating a class that contains a single float which I then aggregate into my lists), unless someone can tell me how to do it properly. End Edit Here's my CreateSessionFactory method, if that helps formulate a reply... private static ISessionFactory CreateSessionFactory() { ISessionFactory sessionFactory = null; const string autoMapExportDir = "AutoMapExport"; if( !Directory.Exists(autoMapExportDir) ) Directory.CreateDirectory(autoMapExportDir); try { var autoPersistenceModel = AutoMap.AssemblyOf<DlsAppOverlordExportRunData>() .Where(t => t.Namespace == "DlsAppAutomapped") .Conventions.Add( DefaultCascade.All() ) ; sessionFactory = Fluently.Configure() .Database(SQLiteConfiguration.Standard .UsingFile(DbFile) .ShowSql() ) .Mappings(m => m.AutoMappings.Add(autoPersistenceModel) .ExportTo(autoMapExportDir) ) .ExposeConfiguration(BuildSchema) .BuildSessionFactory() ; } catch (Exception e) { Debug.WriteLine(e); } return sessionFactory; }

    Read the article

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