Search Results

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

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

  • How to set connection string dynamically in NHibernate

    - by jcreddy
    Hi I want assign connection string for NHibernate using following code and getting exception (bold). log4net.Config.DOMConfigurator.Configure(); Configuration config = new Configuration(); IDictionary props = new Hashtable(); props["hibernate.connection.provider"] = "NHibernate.Connection.DriverConnectionProvider"; props["hibernate.dialect"] = "NHibernate.Dialect.MsSql2000Dialect"; props["hibernate.connection.driver_class"] = "NHibernate.Driver.SqlClientDriver"; props["hibernate.connection.connection_string"] = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Sample;Data Source=HYDHTC92318D\SQLEXPRESS"; props["hibernate.connection.current_session_context_class"] = "web"; props["hibernate.connection.show_sql"] = "true"; props["hibernate.connection.proxyfactoryfactory.factory_class"] = "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"; foreach (DictionaryEntry de in props) { config.SetProperty(de.Key.ToString(), de.Value.ToString()); } config.AddAssembly("nhibernator"); factory = config.BuildSessionFactory(); session = factory.OpenSession(); The ProxyFactoryFactory was not configured. Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers. Example: NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu Example: NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle Please let me know the solution. Regards JCReddy

    Read the article

  • NHibernate Criteria

    - by Vamsi
    public class A { public string aname {get; set;} public string aId {get; set;} public string bId {get; set;} } public class B { public string bId {get; set;} public string bname {get; set;} public string cId {get; set;} } public class C { public string cId {get; set;} public string cfirstname {get; set;} public string clastname {get; set;} } public class abcDTO { public string aname {get; set;} public string bname {get; set;} public string clastname {get; set;} } Evetually the query which I am looking is SELECT a.aid, b.bname, c.clastname FROM A thisa inner join B thisb on thisa.bid=thisb.bid inner join C thisc on thisb.cid=thisc.cid and this_.POLICY_SEARCH_NBR like '%-996654%' The criteria which I am trying is, Please let me know the best possible way to write a criteria so that I can get the abcdto object as result var policyInsuranceBusiness = DetachedCriteria.For() .SetProjection(Projections.Property("a.aid")) .Add(Restrictions.Like("a.aid", "1-SAP-3-996654", MatchMode.Anywhere)) .CreateCriteria("b.bid", "b", JoinType.InnerJoin) .SetProjection(Projections.Property("b.bname")) // ERROR OUT - COULD NOT RESOLVE PROPERTY .CreateCriteria("c.cid", "c", JoinType.InnerJoin) .SetProjection(Projections.Property("c.clastname")); // ERROR - COULD NOT RESOLVE PROPERTY IList plo = policyInsuranceBusiness.GetExecutableCriteria(_session).SetResultTransformer(NHibernate.Transform.Transformers .AliasToBean();

    Read the article

  • How to Specify Columntype in fluent nHibernate?

    - by Bipul
    I have a class CaptionItem public class CaptionItem { public virtual int SystemId { get; set; } public virtual int Version { get; set; } protected internal virtual IDictionary<string, string> CaptionValues {get; private set;} } I am using following code for nHibernate mapping Id(x => x.SystemId); Version(x => x.Version); Cache.ReadWrite().IncludeAll(); HasMany(x => x.CaptionValues) .KeyColumn("CaptionItem_Id") .AsMap<string>(idx => idx.Column("CaptionSet_Name"), elem => elem.Column("Text")) .Not.LazyLoad() .Cascade.Delete() .Table("CaptionValue") .Cache.ReadWrite().IncludeAll(); So in database two tables get created. One CaptionValue and other CaptionItem. In CaptionItem table has three columns 1. CaptionItem_Id int 2. Text nvarchar(255) 3. CaptionSet_Name nvarchar(255) Now, my question is how can I make the columnt type of Text to nvarchar(max)? Thanks in advance.

    Read the article

  • Fluent NHibernate Repository with subclasses

    - by reallyJim
    Having some difficulty understanding the best way to implement subclasses with a generic repository using Fluent NHibernate. I have a base class and two subclasses, say: public abstract class Person { public virtual int PersonId { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } } public class Student : Person { public virtual decimal GPA { get; set; } } public class Teacher : Person { public virtual decimal Salary { get; set; } } My Mappings are as follows: public class PersonMap : ClassMap { public PersonMap() { Table("Persons"); Id(x => x.PersonId).GeneratedBy.Identity(); Map(x => x.FirstName); Map(x => x.LastName); } } public class StudentMap : SubclassMap<Student> { public StudentMap() { Table("Students"); KeyColumn("PersonId"); Map(x => x.GPA); } } public class TeacherMap : SubclassMap<Teacher> { public TeacherMap() { Table("Teachers"); KeyColumn("PersonId"); Map(x => x.Salary); } } I use a generic repository to save/retreive/update the entities, and it works great--provided I'm working with Repository--where I already know that I'm working with students or working with teachers. The problem I run into is this: What happens when I have an ID, and need to determine the TYPE of person? If a user comes to my site as PersonId = 23, how do I go about figuring out which type of person it is?

    Read the article

  • NHibernate One to One Foreign Key ON DELETE CASCADE

    - by xll
    I need to implement One-to-one association between Project and ProjecSettings using fluent NHibernate: public class ProjectMap : ClassMap<Project> { public ProjectMap() { Id(x => x.Id) .UniqueKey(MapUtils.Col<Project>(x => x.Id)) .GeneratedBy.HiLo("NHHiLoIdentity", "NextHiValue", "1000", string.Format("[EntityName] = '[{0}]'", MapUtils.Table<Project>())) .Not.Nullable(); HasOne(x => x.ProjectSettings) .PropertyRef(x => x.Project); } } public class ProjectSettingsMap : ClassMap<ProjectSettings> { public ProjectSettingsMap() { Id(x => x.Id) .UniqueKey(MapUtils.Col<ProjectSettings>(x => x.Id)) .GeneratedBy.HiLo("NHHiLoIdentity", "NextHiValue", "1000", string.Format("[EntityName] = '[{0}]'", MapUtils.Table<ProjectSettings>())); References(x => x.Project) .Column(MapUtils.Ref<ProjectSettings, Project>(p => p.Project, p => p.Id)) .Unique() .Not.Nullable(); } } This results in the following sql for Project Settings: CREATE TABLE ProjectSettings ( Id bigint PRIMARY KEY NOT NULL, Project_Project_Id bigint NOT NULL UNIQUE, /* Foreign keys */ FOREIGN KEY (Project_Project_Id) REFERENCES Project() ON DELETE NO ACTION ON UPDATE NO ACTION ); What I am trying to achieve is to have ON DELETE CASCADE for the FOREIGN KEY (Project_Project_Id), so that when the project is deleted through sql query, it's settings are deleted too. How can I achieve this ? EDIT: I know about Cascade.Delete() option, but it's not what I need. Is there any way to intercept the FK statement generation?

    Read the article

  • [nHibernate] casting string to bool using nHibernate Criteria

    - by code-zoop
    I have an nHibernate query using Criteria, and I am trying to cast a string to bool in the query itself. I have done the same with casting a string to int, and that works well (the "DataField" property is "1" as a string): var result = Session .CreateCriteria<Car>() .Add(Restrictions.Eq((Projections.Cast(NHibernateUtil.Int32, Projections.Property("DataField"), 1)) .List<Car>(); tx.Commit(); But I am trying to do the same with bool, but I do not get the expected result: var result = Session .CreateCriteria<Car>() .Add(Restrictions.Eq((Projections.Cast(NHibernateUtil.bool, Projections.Property("DataField"), true)) .List<Car>(); tx.Commit(); "DataField" is the string "True", but the result in an empty list, where it should contain 100 elements with the "DataField" property string set to "True". I have tried with the string "true", and "1", but the result is still an empty List. [EDIT] As Commented below, I could check for the string "True" or "False", but I would say this is a more general question than just for the Boolean. Note that the idea is to have some sort of key value representation of the data, where the value can be different data types. I need the value table to contain all data, so storing the data as string seems like the cleanest solution! I have been able to use the method above to store both int and double as string, and to the cast in the query, but I have not succeeded using the same method for DateDime and Boolean. And for DateTime it is crucial to have the actual DateTime object. How can I make the cast from string to bool, and string to DateTime work in the queries? Thanks

    Read the article

  • Specify Columntype in nhibernate

    - by Bipul
    I have a class CaptionItem public class CaptionItem { public virtual int SystemId { get; set; } public virtual int Version { get; set; } protected internal virtual IDictionary<string, string> CaptionValues {get; private set;} } I am using following code for nHibernate mapping Id(x => x.SystemId); Version(x => x.Version); Cache.ReadWrite().IncludeAll(); HasMany(x => x.CaptionValues) .KeyColumn("CaptionItem_Id") .AsMap<string>(idx => idx.Column("CaptionSet_Name"), elem => elem.Column("Text")) .Not.LazyLoad() .Cascade.Delete() .Table("CaptionValue") .Cache.ReadWrite().IncludeAll(); So in database two tables get created. One CaptionValue and other CaptionItem. In CaptionItem table has three columns 1. CaptionItem_Id int 2. Text nvarchar(255) 3. CaptionSet_Name nvarchar(255) Now, my question is how can I make the columnt type of Text to nvarchar(max)? Thanks in advance.

    Read the article

  • Conditional row count in linq to nhibernate doesn't work

    - by Lucasus
    I want to translate following simple sql query into Linq to NHibernate: SELECT NewsId ,sum(n.UserHits) as 'HitsNumber' ,sum(CASE WHEN n.UserHits > 0 THEN 1 ELSE 0 END) as 'VisitorsNumber' FROM UserNews n GROUP BY n.NewsId My simplified UserNews class: public class AktualnosciUzytkownik { public virtual int UserNewsId { get; set; } public virtual int UserHits { get; set; } public virtual User User { get; set; } // UserId key in db table public virtual News News { get; set; } // NewsId key in db table } I've written following linq query: var hitsPerNews = (from n in Session.Query<UserNews>() group n by n.News.NewsId into g select new { NewsId = g.Key, HitsNumber = g.Sum(x => x.UserHits), VisitorsNumber = g.Count(x => x.UserHits > 0) }).ToList(); But generated sql just ignores my x => x.UserHits > 0 statement and makes unnecessary 'left outer join': SELECT news1_.NewsId AS col_0_0_, CAST(SUM(news0_.UserHits) AS INT) AS col_1_0_, CAST(COUNT(*) AS INT) AS col_2_0_ FROM UserNews news0_ LEFT OUTER JOIN News news1_ ON news0_.NewsId=news1_.NewsId GROUP BY news1_.NewsId How Can I fix or workaround this issue? Maybe this can be done better with QueryOver syntax?

    Read the article

  • NHibernate Tools

    - by Ricardo Peres
    Felice Pollano is the author of a two great new tools for working with NHibernate: NH Workbench: an IDE for writing HQL queries against a model db2hbm: generation of .hbm.xml files from a database (currently only SQL Server, more to come) I suggest you give them a try and give Felix your feedback!

    Read the article

  • NHibernate Pitfalls: Fetch and Paging

    - by Ricardo Peres
    This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. NHibernate allows you to force loading additional references (many to one, one to one) or collections (one to many, many to many) in a query. You must know, however, that this is incompatible with paging. It’s easy to see why. Let’s say you want to get 5 products starting on the fifth, you can issue the following LINQ query: 1: session.Query<Product>().Take(5).Skip(5).ToList(); Will product this SQL in SQL Server: 1: SELECT 2: TOP (@p0) product1_4_, 3: name4_, 4: price4_ 5: FROM 6: (select 7: product0_.product_id as product1_4_, 8: product0_.name as name4_, 9: product0_.price as price4_, 10: ROW_NUMBER() OVER( 11: ORDER BY 12: CURRENT_TIMESTAMP) as __hibernate_sort_row 13: from 14: product product0_) as query 15: WHERE 16: query.__hibernate_sort_row > @p1 17: ORDER BY If, however, you wanted to bring as well the associated order details, you might be tempted to try this: 1: session.Query<Product>().Fetch(x => x.OrderDetails).Take(5).Skip(5).ToList(); Which, in turn, will produce this SQL: 1: SELECT 2: TOP (@p0) product1_4_0_, 3: order1_3_1_, 4: name4_0_, 5: price4_0_, 6: order2_3_1_, 7: product3_3_1_, 8: quantity3_1_, 9: product3_0__, 10: order1_0__ 11: FROM 12: (select 13: product0_.product_id as product1_4_0_, 14: orderdetai1_.order_detail_id as order1_3_1_, 15: product0_.name as name4_0_, 16: product0_.price as price4_0_, 17: orderdetai1_.order_id as order2_3_1_, 18: orderdetai1_.product_id as product3_3_1_, 19: orderdetai1_.quantity as quantity3_1_, 20: orderdetai1_.product_id as product3_0__, 21: orderdetai1_.order_detail_id as order1_0__, 22: ROW_NUMBER() OVER( 23: ORDER BY 24: CURRENT_TIMESTAMP) as __hibernate_sort_row 25: from 26: product product0_ 27: left outer join 28: order_detail orderdetai1_ 29: on product0_.product_id=orderdetai1_.product_id 30: ) as query 31: WHERE 32: query.__hibernate_sort_row > @p1 33: ORDER BY 34: query.__hibernate_sort_row; However, because of the JOIN, what happens is that, if your products have more than one order details, you will get several records – one per order detail – per product, which means that pagination will be broken. There is an workaround, which forces you to write your LINQ query in another way: 1: session.Query<OrderDetail>().Where(x => session.Query<Product>().Select(y => y.ProductId).Take(5).Skip(5).Contains(x.Product.ProductId)).Select(x => x.Product).ToList() Or, using HQL: 1: session.CreateQuery("select od.Product from OrderDetail od where od.Product.ProductId in (select p.ProductId from Product p skip 5 take 5)").List<Product>(); The generated SQL will then be: 1: select 2: product1_.product_id as product1_4_, 3: product1_.name as name4_, 4: product1_.price as price4_ 5: from 6: order_detail orderdetai0_ 7: left outer join 8: product product1_ 9: on orderdetai0_.product_id=product1_.product_id 10: where 11: orderdetai0_.product_id in ( 12: SELECT 13: TOP (@p0) product_id 14: FROM 15: (select 16: product2_.product_id, 17: ROW_NUMBER() OVER( 18: ORDER BY 19: CURRENT_TIMESTAMP) as __hibernate_sort_row 20: from 21: product product2_) as query 22: WHERE 23: query.__hibernate_sort_row > @p1 24: ORDER BY 25: query.__hibernate_sort_row); Which will get you what you want: for 5 products, all of their order details.

    Read the article

  • Lesser Known NHibernate Session Methods

    - by Ricardo Peres
    The NHibernate ISession, the core of NHibernate usage, has some methods which are quite misunderstood and underused, to name a few, Merge, Persist, Replicate and SaveOrUpdateCopy. Their purpose is: Merge: copies properties from a transient entity to an eventually loaded entity with the same id in the first level cache; if there is no loaded entity with the same id, one will be loaded and placed in the first level cache first; if using version, the transient entity must have the same version as in the database; Persist: similar to Save or SaveOrUpdate, attaches a maybe new entity to the session, but does not generate an INSERT or UPDATE immediately and thus the entity does not get a database-generated id, it will only get it at flush time; Replicate: copies an instance from one session to another session, perhaps from a different session factory; SaveOrUpdateCopy: attaches a transient entity to the session and tries to save it. Here are some samples of its use. ISession session = ...; AuthorDetails existingDetails = session.Get<AuthorDetails>(1); //loads an entity and places it in the first level cache AuthorDetails detachedDetails = new AuthorDetails { ID = existingDetails.ID, Name = "Changed Name" }; //a detached entity with the same ID as the existing one Object mergedDetails = session.Merge(detachedDetails); //merges the Name property from the detached entity into the existing one; the detached entity does not get attached session.Flush(); //saves the existingDetails entity, since it is now dirty, due to the change in the Name property AuthorDetails details = ...; ISession session = ...; session.Persist(details); //details.ID is still 0 session.Flush(); //saves the details entity now and fetches its id ISessionFactory factory1 = ...; ISessionFactory factory2 = ...; ISession session1 = factory1.OpenSession(); ISession session2 = factory2.OpenSession(); AuthorDetails existingDetails = session1.Get<AuthorDetails>(1); //loads an entity session2.Replicate(existingDetails, ReplicationMode.Overwrite); //saves it into another session, overwriting any possibly existing one with the same id; other options are Ignore, where any existing record with the same id is left untouched, Exception, where an exception is thrown if there is a record with the same id and LatestVersion, where the latest version wins 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 Pitfalls Index

    - by Ricardo Peres
    These are the posts on NHibernate pitfalls I’ve written so far. This post will be updated whenever there are more. The SaveOrUpdate Event Collection Restrictions Specifying Event Listeners in XML Configuration Many to Many and Inverse Bags and Join Lazy Properties in Non-Lazy Entities Adding to a Bag Causes Loading Flushing Changes Private Setter on Id Property

    Read the article

  • Implementing a Repository with NHibernate - Quickstart with NHibernate (part 2)

    - by BobPalmer
    This is the second in a series of tutorials I am working on to help developers quickly get up to speed with NHibernate.  In this tutorial, I'll be focusing on an implementation of a repository pattern. As always, comments, suggestions, and any technical bits I may have missed are always appreciated! You can view the entire article via this Google Docs link: http://docs.google.com/Doc?docid=0AUP-rKyyUMKhZGczejdxeHZfMTVjMnBqYjVnNw&hl=en Enjoy! -Bob

    Read the article

  • Duplicate Items Using Join in NHibernate Map

    - by Colin Bowern
    I am trying to retrieve the individual detail rows without having to create an object for the parent. I have a map which joins a parent table with the detail to achieve this: Table("UdfTemplate"); Id(x => x.Id, "Template_Id"); Map(x => x.FieldCode, "Field_Code"); Map(x => x.ClientId, "Client_Id"); Join("UdfFields", join => { join.KeyColumn("Template_Id"); join.Map(x => x.Name, "COLUMN_NAME"); join.Map(x => x.Label, "DISPLAY_NAME"); join.Map(x => x.IsRequired, "MANDATORY_FLAG") .CustomType<YesNoType>(); join.Map(x => x.MaxLength, "DATA_LENGTH"); join.Map(x => x.Scale, "DATA_SCALE"); join.Map(x => x.Precision, "DATA_PRECISION"); join.Map(x => x.MinValue, "MIN_VALUE"); join.Map(x => x.MaxValue, "MAX_VALUE"); }); When I run the query in NH using: Session.CreateCriteria(typeof(UserDefinedField)) .Add(Restrictions.Eq("FieldCode", code)).List<UserDefinedField>(); I get back the first row three times as opposed to the three individual rows it should return. Looking at the SQL trace in NH Profiler the query appears to be correct. The problem feels like it is in the mapping but I am unsure how to troubleshoot that process. I am about to turn on logging to see what I can find but I thought I would post here in case someone with experience mapping joins knows where I am going wrong.

    Read the article

  • nHibernate storage of an object with self referencing many children and many parents

    - by AdamC
    I have an object called MyItem that references children in the same item. How do I set up an nhibernate mapping file to store this item. public class MyItem { public virtual string Id {get;set;} public virtual string Name {get;set;} public virtual string Version {get;set;} public virtual IList<MyItem> Children {get;set;} } So roughly the hbm.xml would be: <class name="MyItem" table="tb_myitem"> <id name="Id" column="id" type="String" length="32"> <generator class="uuid.hex" /> </id> <property name="Name" column="name" /> <property name="Version" column="version" /> <bag name="Children" cascade="all-delete-orphan" lazy="false"> <key column="children_id" /> <one-to-many class="MyItem" not-found="ignore"/> </bag> </class> This wouldn't work I don't think. Perhaps I need to create another class, say MyItemChildren and use that as the Children member and then do the mapping in that class? This would mean having two tables. One table holds the MyItem and the other table holds references from my item. NOTE: A child item could have many parents.

    Read the article

  • Fluent NHibernate Mappings ClassMap<Entities>....

    - by Pandiya Chendur
    I was going through fluent hibernate getting started tutorial.... In my asp.net mvc web application i have created Entities and Mapping folder as they stated... I created an entity class and i tried to map it my mapping class using this, using System; using System.Collections.Generic; using System.Linq; using System.Web; using FluentNhibernateMVC.Entities; namespace FluentNhibernateMVC.Mappings { public class ClientMap : ClassMap<Client> { } } I cant able to find a ClassMap keyword in my autosuggest list why? This is my entity class using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FluentNhibernateMVC.Entities { public class Client { public int ClientId { get; set; } public string ClientName { get; set; } public string ClientMobNo { get; set; } public string ClientAddress { get; set; } public DateTime CreatedDate { get; set; } public byte IsDeleted { get; set; } public int CreatedBy { get; set; } } } I have added all references to my project...Am i missing some thing...

    Read the article

  • How to fluent-map this (using fluent nhibernate)?

    - by vikasde
    I have two tables in my database "Styles" and "BannedStyles". They have a reference via the ItemNo. Now styles can be banned per store. So if style x is banned at store Y then its very possible that its not banned at store Z or vice verse. What is the best way now to map this to a single entity? Should I be mapping this to a single entity? My Style entity looks like this: public class Style { public virtual int ItemNo { get; set;} public virtual string SKU { get; set; } public virtual string StyleName { get; set; } public virtual string Description { get; set; } public virtual Store Store { get; set; } public virtual bool IsEntireStyleBanned { get; set; } }

    Read the article

  • Connection Error using NHibernate 3.0 with Oracle

    - by Olu Lawrence
    I'm new to NHibernate. My first attempt is to configure and establish connection to Oracle 11.1g using ODP. For this test, I use a test fixture, but I get the following error: Inner exception: "Object reference not set to an instance of an object." Outer exception: Could not create the driver from NHibernate.Driver.OracleDataClientDriver. The test script is shown below: using IBCService.Models; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; using NUnit.Framework; namespace IBCService.Tests { [TestFixture] public class GenerateSchema_Fixture { [Test] public void Can_generate_schema() { var cfg = new Configuration(); cfg.Configure(); cfg.AddAssembly(typeof(Product).Assembly); var fac = new SchemaExport(cfg); fac.Execute(false, true, false); } } } The exception occurs at the last line: fac.Execute(false, true, false); The NHibernate config is shown: <?xml version="1.0" encoding="utf-8"?> <!-- This config use Oracle Data Provider (ODP.NET) --> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" > <session-factory name="IBCService.Tests"> <property name="connection.driver_class"> NHibernate.Driver.OracleDataClientDriver </property> <property name="connection.connection_string"> User ID=TEST;Password=test;Data Source=//RAND23:1521/RAND.PREVALENT.COM </property> <property name="connection.provider"> NHibernate.Connection.DriverConnectionProvider </property> <property name="show_sql">false</property> <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property> <property name="query.substitutions"> true 1, false 0, yes 'Y', no 'N' </property> <property name="proxyfactory.factory_class"> NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu </property> </session-factory> </hibernate-configuration> Now, if I change the NHibernate.Driver.OracleDataClientDriver to NHibernate.Driver.OracleClientDriver (Microsoft provider for Oracle), the test succeed. Once switched back to Oracle provider, whichever version, the test fails with the error stated earlier. I've spent 3 days already trying to figure out what is not in order without success. I hope someone out there could provide useful info on what I am doing wrong.

    Read the article

  • nhibernate/fluenthibernate throws StackOverflowException

    - by Gianluca Colucci
    Hi there! In my project I am using NHibernate/FluentNHibernate, and I am working with two entities, contracts and services. This is my contract type: [Serializable] public partial class TTLCContract { public virtual long? Id { get; set; } // other properties here public virtual Iesi.Collections.Generic.ISet<TTLCService> Services { get; set; } // implementation of Equals // and GetHashCode here } and this is my service type: [Serializable] public partial class TTLCService { public virtual long? Id { get; set; } // other properties here public virtual Activity.Models.TTLCContract Contract { get; set; } // implementation of Equals // and GetHashCode here } Ok, so as you can see, I want my contract object to have many services, and each Service needs to have a reference to the parent Contract. I am using FluentNhibernate. So my mappings file are the following: public TTLCContractMapping() { Table("tab_tlc_contracts"); Id(x => x.Id, "tlc_contract_id"); HasMany(x => x.Services) .Inverse() .Cascade.All() .KeyColumn("tlc_contract_id") .AsSet(); } and public TTLCServiceMapping() { Table("tab_tlc_services"); Id(x => x.Id, "tlc_service_id"); References(x => x.Contract) .Not.Nullable() .Column("tlc_contract_id"); } and here comes my problem: if I retrieve the list of all contracts in the db, it works. if I retrieve the list of all services in a given contract, I get a StackOverflowException.... Do you see anything wrong with what I wrote? Have I made any mistake? Please let me know if you need any additional information. Oh yes, I missed to say... looking at the stacktrace I see the system is loading all the services and then it is loading again the contracts related to those services. I don't really have the necessary experience nor ideas anymore to understand what's going on.. so any help would be really really great! Thanks in advance, Cheers, Gianluca.

    Read the article

  • Fleunt NHibernate not working outside of nunit test fixtures

    - by thorkia
    Okay, here is my problem... I created a Data Layer using the RTM Fluent Nhibernate. My create session code looks like this: _session = Fluently.Configure(). Database(SQLiteConfiguration.Standard.UsingFile("Data.s3db")) .Mappings( m => { m.FluentMappings.AddFromAssemblyOf<ProductMap>(); m.FluentMappings.AddFromAssemblyOf<ProductLogMap>(); }) .ExposeConfiguration(BuildSchema) .BuildSessionFactory(); When I reference the module in a test project, then create a test fixture that looks something like this: [Test] public void CanAddProduct() { var product = new Product {Code = "9", Name = "Test 9"}; IProductRepository repository = new ProductRepository(); repository.AddProduct(product); using (ISession session = OrmHelper.OpenSession()) { var fromDb = session.Get<Product>(product.Id); Assert.IsNotNull(fromDb); Assert.AreNotSame(fromDb, product); Assert.AreEqual(fromDb.Id, product.Id); } My tests pass. When I open up the created SQLite DB, the new Product with Code 9 is in it. the tables for Product and ProductLog are there. Now, when I create a new console application, and reference the same library, do something like this: Product product = new Product() {Code = "10", Name = "Hello"}; IProductRepository repository = new ProductRepository(); repository.AddProduct(product); Console.WriteLine(product.Id); Console.ReadLine(); It doesn't work. I actually get pretty nasty exception chain. To save you lots of head aches, here is the summary: Top Level exception: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.\r\n\r\n The PotentialReasons collection is empty The Inner exception: 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 element in the application configuration file to specify the full name of the assembly. Both the unit test library and the console application reference the exact same version of System.Data.SQLite. Both projects have the exact same DLLs in the debug folder. I even tried copying SQLite DB the unit test library created into the debug directory of the console app, and removed the build schema lines and it still fails If anyone can help me figure out why this won't work outside of my unit tests it would be greatly appreciated. This crazy bug has me at a stand still.

    Read the article

  • many-to-many performance concerns with fluent nhibernate.

    - by Ciel
    I have a situation where I have several many-to-many associations. In the upwards of 12 to 15. Reading around I've seen that it's generally believed that many-to-many associations are not 'typical', yet they are the only way I have been able to create the associations appropriate for my case, so I'm not sure how to optimize any further. Here is my basic scenario. class Page { IList<Tag> Tags { get; set; } IList<Modification> Modifications { get; set; } IList<Aspect> Aspects { get; set; } } This is one of my 'core' classes, and coincidentally one of my core tables. Virtually half of the objects in my code can have an IList<Page>, and some of them have IList<T> where T has its own IList<Page>. As you can see, from an object oriented standpoint, this is not really a problem. But from a database standpoint this begins to introduce a lot of junction tables. So far it has worked fine for me, but I am wondering if anyone has any ideas on how I could improve on this structure. I've spent a long time thinking and in order to achieve the appropriate level of association required, I cannot think of any way to improve it. The only thing I have come up with is to make intermediate classes for each object that has an IList<Page>, but that doesn't really do anything that the HasManyToMany does not already do except introduce another class. It does not extend the functionality and, from what I can tell, it does not improve performance. Any thoughts? I am also concerned about Primary Key limits in this scenario. Most everything needs to be able to have these properties, but the Pages cannot be unique to each object, because they are going to be frequently shared and joined between multiple objects. All relationships are one-sided. (That is, a Page has no knowledge of what owns it). Because of this, I also have no Inverse() mapped HasManyToMany collections. Also, I have read the similar question : Usage of ORMs like NHibernate when there are many associations - performance concerns But it really did not answer my concerns.

    Read the article

  • FluentNHibernate - AutoMappings producing incorrect one-to-many column key

    - by Alberto
    Hi I'm new to NHibernate and FNH and am trying to map these simple classes by using FluentNHibernate AutoMappings feature: public class TVShow : Entity { public virtual string Title { get; set;} public virtual ICollection<Season> Seasons { get; protected set; } public TVShow() { Seasons = new HashedSet<Season>(); } public virtual void AddSeason(Season season) { season.TVShow = this; Seasons.Add(season); } public virtual void RemoveSeason(Season season) { if (!Seasons.Contains(season)) { throw new InvalidOperationException("This TV Show does not contain the given season"); } season.TVShow = null; Seasons.Remove(season); } } public class Season : Entity { public virtual TVShow TVShow { get; set; } public virtual int Number { get; set; } public virtual IList<Episode> Episodes { get; set; } public Season() { Episodes = new List<Episode>(); } public virtual void AddEpisode(Episode episode) { episode.Season = this; Episodes.Add(episode); } public virtual void RemoveEpisode(Episode episode) { if (!Episodes.Contains(episode)) { throw new InvalidOperationException("Episode not found on this season"); } episode.Season = null; Episodes.Remove(episode); } } I'm also using a couple of conventions: public class MyForeignKeyConvention : IReferenceConvention { #region IConvention<IManyToOneInspector,IManyToOneInstance> Members public void Apply(FluentNHibernate.Conventions.Instances.IManyToOneInstance instance) { instance.Column("fk_" + instance.Property.Name); } #endregion } The problem is that FNH is generating the section below for the Seasons property mapping: <bag name="Seasons"> <key> <column name="TVShow_Id" /> </key> <one-to-many class="TVShowsManager.Domain.Season, TVShowsManager.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </bag> The column name above should be fk_TVShow rather than TVShow_Id. If amend the hbm files produced by FNH then the code works. Does anyone know what it's wrong? Thanks in advance.

    Read the article

  • Id property not populated

    - by fingers
    I have an identity mapping like so: Id(x => x.GuidId).Column("GuidId") .GeneratedBy.GuidComb().UnsavedValue(Guid.Empty); When I retrieve an object from the database, the GuidId property of my object is Guid.Empty, not the actual Guid (the property in the class is of type System.Guid). However, all of the other properties in the object are populated just fine. The database field's data type (SQL Server 2005) is uniqueidentifier, and marked as RowGuid. The application that is connecting to the database is a VB.NET Web Site project (not a "Web Application" or "MVC Web Application" - just a regular "Web Site" project). I open the NHibernate session through a custom HttpModule. Here is the HttpModule: public class NHibernateModule : System.Web.IHttpModule { public static ISessionFactory SessionFactory; public static ISession Session; private static FluentConfiguration Configuration; static NHibernateModule() { if (Configuration == null) { string connectionString = cfg.ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString; Configuration = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(cs => cs.Is(connectionString))) .ExposeConfiguration(c => c.Properties.Add("current_session_context_class", "web")) .Mappings(x => x.FluentMappings.AddFromAssemblyOf<LeadMap>().ExportTo("C:\\Mappings")); } SessionFactory = Configuration.BuildSessionFactory(); } public void Init(HttpApplication context) { context.BeginRequest += delegate { Session = SessionFactory.OpenSession(); CurrentSessionContext.Bind(Session); }; context.EndRequest += delegate { CurrentSessionContext.Unbind(SessionFactory); }; } public void Dispose() { Session.Dispose(); } } The strangest part of all, is that from my unit test project, the GuidId property is returned as I would expect. I even rigged it to go for the exact row in the exact database as the web site was hitting. The only differences I can think of between the two projects are The unit test project is in C# Something with the way the session is managed between the HttpModule and my unit tests The configuration for the unit tests is as follows: Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(cs => cs.Is(connectionString))) .Mappings(x => x.FluentMappings.AddFromAssemblyOf<LeadDetailMap>()); I am fresh out of ideas. Any help would be greatly appreciated. Thanks

    Read the article

  • XNA 4.0 - Normal mapping shader - strange texture artifacts

    - by Taylor
    I recently started using custom shader. Shader can do diffuse and specular lighting and normal mapping. But normal mapping is causing really ugly artifacts (some sort of pixeling noise) for textures in greater distance. It looks like this: Image link This is HLSL code: // Matrix float4x4 World : World; float4x4 View : View; float4x4 Projection : Projection; //Textury texture2D ColorMap; sampler2D ColorMapSampler = sampler_state { Texture = <ColorMap>; MinFilter = Anisotropic; MagFilter = Linear; MipFilter = Linear; MaxAnisotropy = 16; }; texture2D NormalMap; sampler2D NormalMapSampler = sampler_state { Texture = <NormalMap>; MinFilter = Anisotropic; MagFilter = Linear; MipFilter = Linear; MaxAnisotropy = 16; }; // Light float4 AmbientColor : Color; float AmbientIntensity; float3 DiffuseDirection : LightPosition; float4 DiffuseColor : Color; float DiffuseIntensity; float4 SpecularColor : Color; float3 CameraPosition : CameraPosition; float Shininess; // The input for the VertexShader struct VertexShaderInput { float4 Position : POSITION0; float2 TexCoord : TEXCOORD0; float3 Normal : NORMAL0; float3 Binormal : BINORMAL0; float3 Tangent : TANGENT0; }; // The output from the vertex shader, used for later processing struct VertexShaderOutput { float4 Position : POSITION0; float2 TexCoord : TEXCOORD0; float3 View : TEXCOORD1; float3x3 WorldToTangentSpace : TEXCOORD2; }; // The VertexShader. VertexShaderOutput VertexShaderFunction(VertexShaderInput input, float3 Normal : NORMAL) { VertexShaderOutput output; float4 worldPosition = mul(input.Position, World); float4 viewPosition = mul(worldPosition, View); output.Position = mul(viewPosition, Projection); output.TexCoord = input.TexCoord; output.WorldToTangentSpace[0] = mul(normalize(input.Tangent), World); output.WorldToTangentSpace[1] = mul(normalize(input.Binormal), World); output.WorldToTangentSpace[2] = mul(normalize(input.Normal), World); output.View = normalize(float4(CameraPosition,1.0) - worldPosition); return output; } // The Pixel Shader float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0 { float4 color = tex2D(ColorMapSampler, input.TexCoord); float3 normalMap = 2.0 *(tex2D(NormalMapSampler, input.TexCoord)) - 1.0; normalMap = normalize(mul(normalMap, input.WorldToTangentSpace)); float4 normal = float4(normalMap,1.0); float4 diffuse = saturate(dot(-DiffuseDirection,normal)); float4 reflect = normalize(2*diffuse*normal-float4(DiffuseDirection,1.0)); float4 specular = pow(saturate(dot(reflect,input.View)), Shininess); return color * AmbientColor * AmbientIntensity + color * DiffuseIntensity * DiffuseColor * diffuse + color * SpecularColor * specular; } // Techniques technique Lighting { pass Pass1 { VertexShader = compile vs_2_0 VertexShaderFunction(); PixelShader = compile ps_2_0 PixelShaderFunction(); } } Any advice? Thanks!

    Read the article

  • Problem with delete operation in many to many relation

    - by Alexey Zakharov
    Hi, I've got to classes Product and Store which have many to many relation I want deleting of store not to cause deleting of related product And deleting of product not to cause deleting of related store. Currently deleting of entity cause exception due to Foreign Key constraint. Here is this classes and their mapping in fluent hibernate: public class Product { public Product() { this.StoresStockedIn = new List<Store>(); } public virtual string Name { get; set; } public virtual double Price { get; set; } public virtual long ProductID { get; set; } public virtual IList<Store> StoresStockedIn { get; set; } } public class Store { public Store() { this.Products = new List<Product>(); this.Staff = new List<Employee>(); } public virtual string Name { get; set; } public virtual IList<Product> Products { get; set; } public virtual IList<Employee> Staff { get; set; } public virtual long StoreID { get; set; } } public class ProductMap : ClassMap<Product> { public ProductMap() { this.Id(x => x.ProductID); this.Map(x => x.Name); this.Map(x => x.Price); this.HasManyToMany(x => x.StoresStockedIn) .Cascade.None() .Table("StoreProduct"); } public class StoreMap : ClassMap<Store> { public StoreMap() { this.Id(x => x.StoreID); this.Map(x => x.Name); this.HasManyToMany(x => x.Products) .Cascade.None() .Inverse() .Table("StoreProduct"); this.HasMany(x => x.Staff) .Cascade.All() .Inverse(); } } Thanks, Alexey Zakharov

    Read the article

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