Search Results

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

Page 3/67 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • fluent nHibernate mapping of subclassed structure

    - by Codezy
    I have a workflow class that has a collection of phases, each phase has a collection of tasks. You can design a workflow that will be used by many engagements. When used in engagement I want to be able to add properties to each class (workflow, phase, and task). For example a task in the designer does not have people assigned, but a task in an engagement would need extra properties like who is assigned to it. I have tried many different approaches using subclasses or interfaces but I just can't get it to map the way I want. Currently I have the engagement level versions as subclasses, but I can't get Engagement phases to map to engagement workflows. Public Class WorkflowMapping Inherits ClassMap(Of Workflow) Sub New() Id(Function(x As Workflow) x.Id).Column("Workflow_Id").GeneratedBy.Identity() Map(Function(x As Workflow) x.Description) Map(Function(x As Workflow) x.Generation) Map(Function(x As Workflow) x.IsActive) HasMany(Function(x As Workflow) x.Phases).Cascade.All() End Sub End Class Public Class EngagementWorkflowMapping Inherits SubclassMap(Of EngagementWorkflow) Sub New() Map(Function(x As EngagementWorkflow) x.ClientNo) Map(Function(x As EngagementWorkflow) x.EngagementNo) End Sub End Class How would you approach mapping this in fluent (or hbm) so that you could load just the workflow base class when designing the flow, or the engagement subclass versions of each when being used by an engagement?

    Read the article

  • Nhibernate/Hibernate, lookup tables and object design

    - by Simon G
    Hi, I've got two tables. Invoice with columns CustomerID, InvoiceDate, Value, InvoiceTypeID (CustomerID and InvoiceDate make up a composite key) and InvoiceType with InvoiceTypeID and InvoiceTypeName columns. I know I can create my objects like: public class Invoice { public virtual int CustomerID { get; set; } public virtual DateTime InvoiceDate { get; set; } public virtual decimal Value { get; set; } public virtual InvoiceType InvoiceType { get; set; } } public class InvoiceType { public virtual InvoiceTypeID { get; set; } public virtual InvoiceTypeName { get; set; } } So the generated sql would look something like: SELECT CustomerID, InvoiceDate, Value, InvoiceTypeID FROM Invoice WHERE CustomerID = x AND InvoiceDate = y SELECT InvoiceTypeID, InvoiceTypeName FROM InvoiceType WHERE InvoiceTypeID = z But rather that having two select queries executed to retrieve the data I would rather have one. I would also like to avoid using child object for simple lookup lists. So my object would look something like: public class Invoice { public virtual int CustomerID { get; set; } public virtual DateTime InvoiceDate { get; set; } public virtual decimal Value { get; set; } public virtual InvoiceTypeID { get; set; } public virtual InvoiceTypeName { get; set; } } And my sql would look something like: SELECT CustomerID, InvoiceDate, Value, InvoiceTypeID FROM Invoice INNER JOIN InvoiceType ON Invoice.InvoiceTypeID = InvoiceType.InvoiceTypeID WHERE CustomerID = x AND InvoiceDate = y My question is how do I create the mapping for this? I've tried using join but this tried to join using CustomerID and InvoiceDate, am I missing something obvious? Thanks

    Read the article

  • Fluent NHibernate automap a HasManyToMany using a generic type

    - by zulkamal
    I have a bunch of domain entities that can be keyword tagged (a Tag is also an entity.) I want to do a normal many-to-many (Tag - TagReview <- Review) table relationship but I don't want to have to create a new concrete relationship on both the Entity and Tag every single time I add a new entity. I was hoping to do a generic based Tag and do this: // Tag public class Tag<T> { public virtual int Id { get; private set; } public virtual string Name { get; set; } public virtual IList<T> Entities { get; set; } public Tag() { Entities = new List<T>(); } } // Review public class Review { public virtual string Id { get; private set; } public virtual string Title { get; set; } public virtual string Content { get; set; } public virtual IList<Tag<Review>> Tags { get; set; } public Review() { Tags = new List<Tag<Review>>(); } } Unfortunately I get an exception: ----> System.ArgumentException : Cannot create an instance of FluentNHibernate.Automapping.AutoMapping`1[Example.Entities.Tag`1[T]] because Type.ContainsGenericParameters is true. I anticipate there will be maybe 5-10 entities so mapping normally would be ok but is there a way to do something like this?

    Read the article

  • NHibernate: Mapping multiple classes from a single table row

    - by Michael Kurtz
    I couldn't find an answer to this specific question. I am trying to keep my domain model object-oriented and re-use objects where possible. I am having an issue determining how to provide a mapping to multiple classes from a single row. Let me explain with an example: I have a single table, call it Customer. A customer has several attributes; but, for brevity, assume it has Id, Name, Address, City, State, ZipCode. I would like to create a Customer and Address class that look like this: public class Customer { public virtual long Id {get;set;} public virtual string Name {get;set;} public virtual Address Address {get;set;} } public class Address { public virtual string Address {get;set;} public virtual string City {get;set;} public virtual string State {get;set;} public virtual string ZipCode {get;set;} } What I am having trouble with is determining what the mapping would be for the Address class within the Customer class. There is no Address table and there isn't a "set" of addresses associated with a Customer. I just want a more object-oriented view of the Customer table in code. There are several other tables that have address information in them and it would be nice to have a reusable Address class to deal with them. Addresses are not shared so breaking all addresses into a separate table with foreign keys seems to be overkill and, actually, more painful since I would need foreign keys to multiple tables. Can someone enlighten me on this type of mapping? Please provide an example if you can. Thanks for any insights! -Mike

    Read the article

  • NHibernate complex order query

    - by manu08
    Here's my simplified domain public class Notification { public Guid ID { get; set; } public string Name { get; set; } public IEnumerable<Location> Locations { get; set; } } public class Location { public Guid Id { get; set; } public string Name { get; set; } public decimal Longitude { get; set; } public decimal Latitude { get; set; } } Notifications and Locations have a many-to-many relationship (defined in table LocationsOnNotification). What I'd like to do is query for the nearest 10 Notifications from a given longitude and latitude. I've been trying to use ICriteria, but I'm not sure how to specify the ordering correctly: return Session.CreateCriteria<Notification>() .SetFirstResult(firstIndex) .SetMaxResults(maxResults) .AddOrder(Order.Asc( WHAT GOES HERE! )) .List<Notification>(); What I've been thinking of so far is adding a formula property to the Location mapping; something like this: <property name='Distance' formula='lots of geometry'/> But I'm not sure if that can take in parameters (since I'd need to pass in the user's location to calculate the distance), plus I'm not sure how to specify it in the Order.Asc clause given that it's a property on a many-to-many association class. Any ideas? Or perhaps I should take a different approach altogether. Thanks in advance!

    Read the article

  • Nhibernate mapping: fixed count multiple members instead of collection

    - by AhmetC
    I don't want to put wheels into a collection. How can i map kind of relation? Class Wheel { int id; Car Owner; } Class Car { int id; Wheel Wheel1; Wheel Wheel2; Wheel Wheel3; Wheel Wheel4; } I tried this but Wheelmap.Owner comes always null : Class WheelMap : ClassMap<Wheel> { Id(x=>x.Id); References(x=>x.Owner); } Class CarMap : ClassMap<Car> { Id(x=>x.Id); References(x=>x.Wheel1).Cascade.All(); References(x=>x.Wheel2).Cascade.All(); References(x=>x.Wheel3).Cascade.All(); References(x=>x.Wheel4).Cascade.All(); }

    Read the article

  • Nhibernate - getting single column from other table

    - by Muhammad Akhtar
    I have following tables Employee: ID,CompanyID,Name //CompanyID is foriegn key of Company Table Company: CompanyID, Name I want to map this to the following class: public class Employee { public virtual Int ID { get; set; } public virtual Int CompanyID { get; set; } public virtual string Name { get; set; } public virtual string CompanyName { get; set; } protected Employee() { } } here is my xml class <class name="Employee" table="Employee" lazy="true"> <id name="Id" type="Int32" column="Id"> <generator class="native" /> </id> <property name="CompanyID" column="CompanyID" type="Int32" not-null="false"/> <property name="Name" column="Name" type="String" length="100" not-null="false"/> What I need to add in xml class to map CompanyName in my result? here is my code... public ArrayList getTest() { ISession session = NHibernateHelper.GetCurrentSession(); string query = "select Employee.*,(Company.Name)CompanyName from Employee inner join Employee on Employee.CompanyID = Company.CompanyID"; ArrayList document = (ArrayList)session.CreateSQLQuery(query, "Employee", typeof(Document)).List(); return document; } but in the returned result, I am getting CompanyName is null is result set and other columns are fine. Note:In DB, tables don't physical relation Please suggest my solution ------ Thanks

    Read the article

  • Nhibernate: mapping two different properties between the same 2 entities

    - by Carlos Decas
    I have a Class A: public class ClassA { public int ID {get; private set;} public string Code {get; private set;} public ClassB B {get; private set;} public IList<ClassB> ListB {get; private set;} } And a ClassB: public class ClassB { public int ID {get; private set;} public string Code {get; private set;} public ClassA A {get; private set;} //some other attributes... } And the Mappings: public ClassAMap() { Table("ClassA"); Id(classA => classA .ID, "ID").GeneratedBy.Identity(); Map(classA => classA.Code, "Code").Unique().Not.Nullable(); //HERE IS THE PROBLEM: -------- References(classA => classA.B,"IDClassB").Cascade.SaveUpdate(); //----- HasMany(classA => classA.ListB).Table("ClassB").KeyColumn("IDClassA").AsBag().Not.LazyLoad().Inverse().Cascade.AllDeleteOrphan(); } ClassB Mappings: public ClassBMap() { Table("ClassB"); Id(classB => classB.ID).GeneratedBy.Identity(); References(classB => classB.A, "IDClassA").ForeignKey("ID").Cascade.SaveUpdate(); } The mappings for ListB in classA worked ok, because at first the was only ListB property and not B, when i had to map B i tried this: References(classA => classA.B,"IDClassB"); The mapping test failed because B wasn't saved, so i did this: References(classA => classA.B,"IDClassB").Cascade.SaveUpdate(); This time B was saved, but by saving B, classA was inserted two times, by A.B and by B.A. How can i solve this problem? Why does it work for the ListB property and not for the B property? Thanks

    Read the article

  • MVC + Nhibernate + Oracle Schema Configuration

    - by Orkun Balkanci
    Our customer wants us to use a connectionstring with username = "external" and add schemaName "original" infront of our queries like: "select columnA from original.TableA" I dont want to change mapping files which are shared by other projects, tried adding default schema as: <property name="default_schema">original</property> But this doesn't work. Any Help?

    Read the article

  • Nhibernate Fluent domain Object with Id(x => x.id).GeneratedBy.Assigned not saveable

    - by urpcor
    Hi there, I am using for some legacy db the corresponding domainclasses with mappings. Now the Ids of the entities are calculated by some stored Procedure in the DB which gives back the Id for the new row.(Its legacy, I cant change this) Now I create the new entity , set the Id and Call Save. But nothing happens. no exeption. Even NH Profiler does not say a bit. its as the Save call does nothing. I expect that NH thinks that the record is already in the db because its got an Id already. But I am using Id(x = x.id).GeneratedBy.Assigned() and intetionally the Session.Save(object) method. I am confused. I saw so many samples there it worked. does any body have any ideas about it? public class Appendix { public virtual int id { get; set; } public virtual AppendixHierarchy AppendixHierachy { get; set; } public virtual byte[] appendix { get; set; } } public class AppendixMap : ClassMap<Appendix> { public AppendixMap () { WithTable("appendix"); Id(x => x.id).GeneratedBy.Assigned(); References(x => x.AppendixHierachy).ColumnName("appendixHierarchyId"); Map(x => x.appendix); } }

    Read the article

  • Nhibernate:null index column for collection Error

    - by Quintin Par
    I am working a subsonic to NH migration(I can’t change the schema) and while creating the mapping I came across this error null index column for collection: Company.Core.CompanyUser.Addresses My mapping from the User side is mapping.HasMany(x => x.Addresses).AsList().KeyColumn("user_id").Cascade.All().Inverse(); xml <list cascade="all" inverse="true" name="Addresses"> <key> <column name="user_id" /> </key> <index /> <one-to-many class="Company.Core.CompanyAddress, Company.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </list> On the Address side it is mapping.CompositeId().KeyReference(x => x.User, "user_id").KeyProperty(x => x.Type); xml <composite-id mapped="false" unsaved-value="undefined"> <key-property name="Type" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Type" /> </key-property> <key-many-to-one name="User" class="Company.Core.CompanyUser, Company.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"> <column name="user_id" /> </key-many-to-one> </composite-id> When I try to load this collection as user.Addresses I get the index null exception. How do I fix this error?

    Read the article

  • NHibernate.MappingException: No persister for:

    - by Sara Chipps
    Now, before you say it I DID google and my hbm.xml file IS an Embedded Resource. Here is the code I am calling: ISession session = GetCurrentSession(); var returnObject = session.Get<T>(Id); Here is my mapping file for the class: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true"> <id name="ID" column="ID" unsaved-value="0"> <generator class="identity" /> </id> <property name="Name" column="Name" /> <property name="NumberOfBuckets" column="NumberOfBuckets" /> <property name="SearchCriteriaOne" column="SearchCriteriaOne" /> <bag name="_Businesses" cascade="all"> <key column="SubCategoryId"/> <one-to-many class="HQData.Objects.Business, HQData"/> </bag> <bag name="_Buckets" cascade="all"> <key column="SubCategoryId"/> <one-to-many class="HQData.Objects.Bucket, HQData"/> </bag> </class> </hibernate-mapping> Has anyone run to this issue before? I swore that was it after I read it, but no dice. Here is the rest of the error and thanks for your help. MappingException: No persister for: HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id) in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id) in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory() in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e) in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436 I had changed some code and I wasn't adding the Assembly to the config file during runtime. Thanks for your help This has been fixed, I am not F-ing with my NHibernate setup ever again!

    Read the article

  • (Fluent) NHibernate Security Exception - ReflectionPermission

    - by PeterEysermans
    I've upgraded an ASP.Net Web application to the latest build of Fluent NHibernate (1.0.0.636) and the newest version of NHibernate (v2.1.2.4000). I've checked a couple of times that the application is running in Full trust. But I keep getting the following error: Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.] System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0 System.Security.CodeAccessPermission.Demand() +54 System.Reflection.Emit.DynamicMethod.PerformSecurityCheck(Type owner, StackCrawlMark& stackMark, Boolean skipVisibility) +269 System.Reflection.Emit.DynamicMethod..ctor(String name, Type returnType, Type[] parameterTypes, Type owner, Boolean skipVisibility) +81 NHibernate.Bytecode.Lightweight.ReflectionOptimizer.CreateDynamicMethod(Type returnType, Type[] argumentTypes) +165 NHibernate.Bytecode.Lightweight.ReflectionOptimizer.GenerateGetPropertyValuesMethod(IGetter[] getters) +383 NHibernate.Bytecode.Lightweight.ReflectionOptimizer..ctor(Type mappedType, IGetter[] getters, ISetter[] setters) +108 NHibernate.Bytecode.Lightweight.BytecodeProviderImpl.GetReflectionOptimizer(Type mappedClass, IGetter[] getters, ISetter[] setters) +52 NHibernate.Tuple.Component.PocoComponentTuplizer..ctor(Component component) +231 NHibernate.Tuple.Component.ComponentEntityModeToTuplizerMapping..ctor(Component component) +420 NHibernate.Tuple.Component.ComponentMetamodel..ctor(Component component) +402 NHibernate.Mapping.Component.BuildType() +38 NHibernate.Mapping.Component.get_Type() +32 NHibernate.Mapping.SimpleValue.IsValid(IMapping mapping) +39 NHibernate.Mapping.RootClass.Validate(IMapping mapping) +61 NHibernate.Cfg.Configuration.ValidateEntities() +220 NHibernate.Cfg.Configuration.Validate() +16 NHibernate.Cfg.Configuration.BuildSessionFactory() +39 FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory() in d:\Builds\FluentNH\src\FluentNHibernate\Cfg\FluentConfiguration.cs:93 Anyone had a similar error? I've seach the web / stackoverflow / NHibernate forums but only found people who had a problem when running in medium trust mode, not full trust. I've been developing for several months on this application on this machine with previous versions of Fluent NHibernate and NHibernate. The machine I'm running this on is 64-bit, you never know that this is relevant.

    Read the article

  • NHibernate with Framework .NET Framework 2

    - by Daniel Dolz
    Hi. I can not make NHibernate 2.1 work in machines without framework 3.X (basically, windows 2000 SP4, although it happens with XP too). NHibernate doc do no mention this. Maybe you can help? I NEED to make NHibernate 2.1 work in Windows 2000 PCs, so you think this can be done? Thanks! PD: DataBase is SQL 2000/2005. Error is: NHibernate.MappingException: Could not compile the mapping document: Datos.NH_VEN_ComprobanteBF.hbm.xml ---> NHibernate.HibernateException: Could not instantiate dialect class NHibernate.Dialect.MsSql2000Dialect ---> System.Reflection.TargetInvocationException: Se produjo una excepción en el destino de la invocación. ---> System.TypeInitializationException: Se produjo una excepción en el inicializador de tipo de 'NHibernate.NHibernateUtil'. ---> System.TypeLoadException: No se puede cargar el tipo 'System.DateTimeOffset' del ensamblado'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. en NHibernate.Type.DateTimeOffsetType.get_ReturnedClass() en NHibernate.NHibernateUtil..cctor() --- Fin del seguimiento de la pila de la excepción interna --- en NHibernate.Dialect.Dialect..ctor() en NHibernate.Dialect.MsSql2000Dialect..ctor() --- Fin del seguimiento de la pila de la excepción interna --- en System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) en System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) en System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) en System.Activator.CreateInstance(Type type, Boolean nonPublic) en NHibernate.Bytecode.ActivatorObjectsFactory.CreateInstance(Type type) en NHibernate.Dialect.Dialect.InstantiateDialect(String dialectName) --- Fin del seguimiento de la pila de la excepción interna --- en NHibernate.Dialect.Dialect.InstantiateDialect(String dialectName) en NHibernate.Dialect.Dialect.GetDialect(IDictionary`2 props) en NHibernate.Cfg.Configuration.AddValidatedDocument(NamedXmlDocument doc) --- Fin del seguimiento de la pila de la excepción interna --- en NHibernate.Cfg.Configuration.LogAndThrow(Exception exception) en NHibernate.Cfg.Configuration.AddValidatedDocument(NamedXmlDocument doc) en NHibernate.Cfg.Configuration.ProcessMappingsQueue() and continues...

    Read the article

  • How do you map a composite id to a composite user type with Fluent NHibernate?

    - by gabe
    i'm working w/ a legacy database is set-up stupidly with an index composed of a char id column and two char columns which make up a date and time, respectively. I have created a icompositeusertype for the date and time columns to map to a single .NET DateTime property on my entity, which works by itself when not part of the id. i need to somehow use a composite id with key property mapping that includes my icompositeusertype for mapping to the two char date and time columns. Apparently w/ my version of Fluent NHibernate, CompositeIdentityPart doesn't have a CustomTypeIs() method, so i can't just do the following in my override: mapping.UseCompositeId() .WithKeyProperty(x => x.Id, CommonDatabaseFieldNames.Id) .WithKeyProperty(x => x.FileCreationDateTime) .CustomTypeIs<FileCreationDateTimeType>(); is something like this even possible w/ NHibernate let alone Fluent? I haven't been able to find anything on this.

    Read the article

  • NHibernate.QueryException with dynamic-component

    - by Ken
    OK, this is going to be kind of a long shot, since it's a big system (which I don't claim to fully understand, yet), and the problem might not be with NHibernate itself, and I'm even having trouble reproducing it, but... I've got a class with a <dynamic-component section, and when I run a query on it (through my ASP.NET MVC app), it fails, but only sometimes. (Yeah, the worst kind!) The exception I'm seeing is: NHibernate.QueryException: could not resolve property: Attributes.MyAttributeName of: MyClassName at NHibernate.Persister.Entity.AbstractPropertyMapping.GetColumns(String propertyName) at NHibernate.Persister.Entity.AbstractPropertyMapping.ToColumns(String alias, String propertyName) at NHibernate.Persister.Entity.BasicEntityPropertyMapping.ToColumns(String alias, String propertyName) at NHibernate.Persister.Entity.AbstractEntityPersister.ToColumns(String alias, String propertyName) at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetColumns(String propertyName, ICriteria subcriteria) at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetColumnsUsingProjection(ICriteria subcriteria, String propertyName) at NHibernate.Criterion.CriterionUtil.GetColumnNamesUsingPropertyName(ICriteriaQuery criteriaQuery, ICriteria criteria, String propertyName, Object value, ICriterion critertion) at NHibernate.Criterion.CriterionUtil.GetColumnNamesForSimpleExpression(String propertyName, IProjection projection, ICriteriaQuery criteriaQuery, ICriteria criteria, IDictionary`2 enabledFilters, ICriterion criterion, Object value) at NHibernate.Criterion.SimpleExpression.ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary`2 enabledFilters) at NHibernate.Loader.Criteria.CriteriaQueryTranslator.GetWhereCondition(IDictionary`2 enabledFilters) at NHibernate.Loader.Criteria.CriteriaJoinWalker..ctor(IOuterJoinLoadable persister, CriteriaQueryTranslator translator, ISessionFactoryImplementor factory, CriteriaImpl criteria, String rootEntityName, IDictionary`2 enabledFilters) at NHibernate.Loader.Criteria.CriteriaLoader..ctor(IOuterJoinLoadable persister, ISessionFactoryImplementor factory, CriteriaImpl rootCriteria, String rootEntityName, IDictionary`2 enabledFilters) at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) at NHibernate.Impl.CriteriaImpl.List(IList results) at NHibernate.Impl.CriteriaImpl.UniqueResult[T]() ...my code below here... Can anybody explain exactly what this QueryException means, i.e., so I can have an idea of what exactly it thinks is going wrong? Thanks!

    Read the article

  • converting to Fluent NHibernate sessionmanager

    - by czuroski
    Hello, I am changing my application to use Fluent NHibernate. I have created my Fluent mapping files and have now moved onto configuring my Session Manager. Currently, I use the following code - private ISessionFactory GetSessionFactory() { return (new Configuration()).Configure().BuildSessionFactory(); } Along with my hibernate.cfg.xml - <?xml version="1.0" encoding="utf-8" ?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" > <session-factory> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="dialect">NHibernate.Dialect.InformixDialect1000</property> <property name="connection.driver_class">NHibernate.Driver.OleDbDriver</property> <property name="connection.connection_string">Provider=Ifxoledbc.2;Password=mypass;Persist Security Info=True;User ID=myid;Data Source=mysource</property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property> <property name="show_sql">false</property> <mapping assembly="DataTransfer" /> </session-factory> </hibernate-configuration> Does anyone know how I could transfer this to Fluent? The problem I have having is with the Database portion of the configuration. Thanks for any thoughts.

    Read the article

  • In NHibernate (Fluent), How do you map a property on referenced object into parent object?

    - by JChristian
    I want to map the Name column from the Child table into the Parent object. How do you do this (using Fluent NHibernate)? public class Parent { public int Key { get; set; } public string ChildName { get; set; } } Tables +--------------+ +------------------+ | Parent | | Child | +--------------+ +------------------+ | Key INT | +--->| Key INT | | ChildKey INT |-----+ | Name VARCHAR(20) | +--------------+ +------------------+

    Read the article

  • What is wrong with the following Fluent NHibernate Mapping ?

    - by ashraf
    Hi, I have 3 tables (Many to Many relationship) Resource {ResourceId, Description} Role {RoleId, Description} Permission {ResourceId, RoleId} I am trying to map above tables in fluent-nHibernate. This is what I am trying to do. var aResource = session.Get<Resource>(1); // 2 Roles associated (Role 1 and 2) var aRole = session.Get<Role>(1); aResource.Remove(aRole); // I try to delete just 1 role from permission. But the sql generated here is (which is wrong) Delete from Permission where ResourceId = 1 Insert into Permission (ResourceId, RoleId) values (1, 2); Instead of (right way) Delete from Permission where ResourceId = 1 and RoleId = 1 Why nHibernate behave like this? What wrong with the mapping? I even tried with Set instead of IList. Here is the full code. Entities public class Resource { public virtual string Description { get; set; } public virtual int ResourceId { get; set; } public virtual IList<Role> Roles { get; set; } public Resource() { Roles = new List<Role>(); } } public class Role { public virtual string Description { get; set; } public virtual int RoleId { get; set; } public virtual IList<Resource> Resources { get; set; } public Role() { Resources = new List<Resource>(); } } Mapping Here // Mapping .. public class ResourceMap : ClassMap<Resource> { public ResourceMap() { Id(x => x.ResourceId); Map(x => x.Description); HasManyToMany(x => x.Roles).Table("Permission"); } } public class RoleMap : ClassMap<Role> { public RoleMap() { Id(x => x.RoleId); Map(x => x.Description); HasManyToMany(x => x.Resources).Table("Permission"); } } Program static void Main(string[] args) { var factory = CreateSessionFactory(); using (var session = factory.OpenSession()) { using (var tran = session.BeginTransaction()) { var aResource = session.Get<Resource>(1); var aRole = session.Get<Role>(1); aResource.Remove(aRole); session.Save(a); session.Flush(); tran.Commit(); } } } private static ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString("server=(local);database=Store;Integrated Security=SSPI")) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>() .Conventions.Add<CustomForeignKeyConvention>()) .BuildSessionFactory(); } public class CustomForeignKeyConvention : ForeignKeyConvention { protected override string GetKeyName(FluentNHibernate.Member property, Type type) { return property == null ? type.Name + "Id" : property.Name + "Id"; } } Thanks, Ashraf.

    Read the article

  • NHibernate Conventions

    - by Ricardo Peres
    Introduction It seems that nowadays everyone loves conventions! Not the ones that you go to, but the ones that you use, that is! It just happens that NHibernate also supports conventions, and we’ll see exactly how. Conventions in NHibernate are supported in two ways: Naming of tables and columns when not explicitly indicated in the mappings; Full domain mapping. Naming of Tables and Columns Since always NHibernate has supported the concept of a naming strategy. A naming strategy in NHibernate converts class and property names to table and column names and vice-versa, when a name is not explicitly supplied. In concrete, it must be a realization of the NHibernate.Cfg.INamingStrategy interface, of which NHibernate includes two implementations: DefaultNamingStrategy: the default implementation, where each column and table are mapped to identically named properties and classes, for example, “MyEntity” will translate to “MyEntity”; ImprovedNamingStrategy: underscores (_) are used to separate Pascal-cased fragments, for example, entity “MyEntity” will be mapped to a “my_entity” table. The naming strategy can be defined at configuration level (the Configuration instance) by calling the SetNamingStrategy method: 1: cfg.SetNamingStrategy(ImprovedNamingStrategy.Instance); Both the DefaultNamingStrategy and the ImprovedNamingStrategy classes offer singleton instances in the form of Instance static fields. DefaultNamingStrategy is the one NHibernate uses, if you don’t specify one. Domain Mapping In mapping by code, we have the choice of relying on conventions to do the mapping automatically. This means a class will inspect our classes and decide how they will relate to the database objects. The class that handles conventions is NHibernate.Mapping.ByCode.ConventionModelMapper, a specialization of the base by code mapper, NHibernate.Mapping.ByCode.ModelMapper. The ModelMapper relies on an internal SimpleModelInspector to help it decide what and how to map, but the mapper lets you override its decisions.  You apply code conventions like this: 1: //pick the types that you want to map 2: IEnumerable<Type> types = Assembly.GetExecutingAssembly().GetExportedTypes(); 3:  4: //conventions based mapper 5: ConventionModelMapper mapper = new ConventionModelMapper(); 6:  7: HbmMapping mapping = mapper.CompileMappingFor(types); 8:  9: //the one and only configuration instance 10: Configuration cfg = ...; 11: cfg.AddMapping(mapping); This is a very simple example, it lacks, at least, the id generation strategy, which you can add by adding an event handler like this: 1: mapper.BeforeMapClass += (IModelInspector modelInspector, Type type, IClassAttributesMapper classCustomizer) => 2: { 3: classCustomizer.Id(x => 4: { 5: //set the hilo generator 6: x.Generator(Generators.HighLow); 7: }); 8: }; The mapper will fire events like this whenever it needs to get information about what to do. And basically this is all it takes to automatically map your domain! It will correctly configure many-to-one and one-to-many relations, choosing bags or sets depending on your collections, will get the table and column names from the naming strategy we saw earlier and will apply the usual defaults to all properties, such as laziness and fetch mode. However, there is at least one thing missing: many-to-many relations. The conventional mapper doesn’t know how to find and configure them, which is a pity, but, alas, not difficult to overcome. To start, for my projects, I have this rule: each entity exposes a public property of type ISet<T> where T is, of course, the type of the other endpoint entity. Extensible as it is, NHibernate lets me implement this very easily: 1: mapper.IsOneToMany((MemberInfo member, Boolean isLikely) => 2: { 3: Type sourceType = member.DeclaringType; 4: Type destinationType = member.GetMemberFromDeclaringType().GetPropertyOrFieldType(); 5:  6: //check if the property is of a generic collection type 7: if ((destinationType.IsGenericCollection() == true) && (destinationType.GetGenericArguments().Length == 1)) 8: { 9: Type destinationEntityType = destinationType.GetGenericArguments().Single(); 10:  11: //check if the type of the generic collection property is an entity 12: if (mapper.ModelInspector.IsEntity(destinationEntityType) == true) 13: { 14: //check if there is an equivalent property on the target type that is also a generic collection and points to this entity 15: PropertyInfo collectionInDestinationType = destinationEntityType.GetProperties().Where(x => (x.PropertyType.IsGenericCollection() == true) && (x.PropertyType.GetGenericArguments().Length == 1) && (x.PropertyType.GetGenericArguments().Single() == sourceType)).SingleOrDefault(); 16:  17: if (collectionInDestinationType != null) 18: { 19: return (false); 20: } 21: } 22: } 23:  24: return (true); 25: }); 26:  27: mapper.IsManyToMany((MemberInfo member, Boolean isLikely) => 28: { 29: //a relation is many to many if it isn't one to many 30: Boolean isOneToMany = mapper.ModelInspector.IsOneToMany(member); 31: return (!isOneToMany); 32: }); 33:  34: mapper.BeforeMapManyToMany += (IModelInspector modelInspector, PropertyPath member, IManyToManyMapper collectionRelationManyToManyCustomizer) => 35: { 36: Type destinationEntityType = member.LocalMember.GetPropertyOrFieldType().GetGenericArguments().First(); 37: //set the mapping table column names from each source entity name plus the _Id sufix 38: collectionRelationManyToManyCustomizer.Column(destinationEntityType.Name + "_Id"); 39: }; 40:  41: mapper.BeforeMapSet += (IModelInspector modelInspector, PropertyPath member, ISetPropertiesMapper propertyCustomizer) => 42: { 43: if (modelInspector.IsManyToMany(member.LocalMember) == true) 44: { 45: propertyCustomizer.Key(x => x.Column(member.LocalMember.DeclaringType.Name + "_Id")); 46:  47: Type sourceType = member.LocalMember.DeclaringType; 48: Type destinationType = member.LocalMember.GetPropertyOrFieldType().GetGenericArguments().First(); 49: IEnumerable<String> names = new Type[] { sourceType, destinationType }.Select(x => x.Name).OrderBy(x => x); 50:  51: //set inverse on the relation of the alphabetically first entity name 52: propertyCustomizer.Inverse(sourceType.Name == names.First()); 53: //set mapping table name from the entity names in alphabetical order 54: propertyCustomizer.Table(String.Join("_", names)); 55: } 56: }; We have to understand how the conventions mapper thinks: For each collection of entities found, it will ask the mapper if it is a one-to-many; in our case, if the collection is a generic one that has an entity as its generic parameter, and the generic parameter type has a similar collection, then it is not a one-to-many; Next, the mapper will ask if the collection that it now knows is not a one-to-many is a many-to-many; Before a set is mapped, if it corresponds to a many-to-many, we set its mapping table. Now, this is tricky: because we have no way to maintain state, we sort the names of the two endpoint entities and we combine them with a “_”; for the first alphabetical entity, we set its relation to inverse – remember, on a many-to-many relation, only one endpoint must be marked as inverse; finally, we set the column name as the name of the entity with an “_Id” suffix; Before the many-to-many relation is processed, we set the column name as the name of the other endpoint entity with the “_Id” suffix, as we did for the set. And that’s it. With these rules, NHibernate will now happily find and configure many-to-many relations, as well as all the others. You can wrap this in a new conventions mapper class, so that it is more easily reusable: 1: public class ManyToManyConventionModelMapper : ConventionModelMapper 2: { 3: public ManyToManyConventionModelMapper() 4: { 5: base.IsOneToMany((MemberInfo member, Boolean isLikely) => 6: { 7: return (this.IsOneToMany(member, isLikely)); 8: }); 9:  10: base.IsManyToMany((MemberInfo member, Boolean isLikely) => 11: { 12: return (this.IsManyToMany(member, isLikely)); 13: }); 14:  15: base.BeforeMapManyToMany += this.BeforeMapManyToMany; 16: base.BeforeMapSet += this.BeforeMapSet; 17: } 18:  19: protected virtual Boolean IsManyToMany(MemberInfo member, Boolean isLikely) 20: { 21: //a relation is many to many if it isn't one to many 22: Boolean isOneToMany = this.ModelInspector.IsOneToMany(member); 23: return (!isOneToMany); 24: } 25:  26: protected virtual Boolean IsOneToMany(MemberInfo member, Boolean isLikely) 27: { 28: Type sourceType = member.DeclaringType; 29: Type destinationType = member.GetMemberFromDeclaringType().GetPropertyOrFieldType(); 30:  31: //check if the property is of a generic collection type 32: if ((destinationType.IsGenericCollection() == true) && (destinationType.GetGenericArguments().Length == 1)) 33: { 34: Type destinationEntityType = destinationType.GetGenericArguments().Single(); 35:  36: //check if the type of the generic collection property is an entity 37: if (this.ModelInspector.IsEntity(destinationEntityType) == true) 38: { 39: //check if there is an equivalent property on the target type that is also a generic collection and points to this entity 40: PropertyInfo collectionInDestinationType = destinationEntityType.GetProperties().Where(x => (x.PropertyType.IsGenericCollection() == true) && (x.PropertyType.GetGenericArguments().Length == 1) && (x.PropertyType.GetGenericArguments().Single() == sourceType)).SingleOrDefault(); 41:  42: if (collectionInDestinationType != null) 43: { 44: return (false); 45: } 46: } 47: } 48:  49: return (true); 50: } 51:  52: protected virtual new void BeforeMapManyToMany(IModelInspector modelInspector, PropertyPath member, IManyToManyMapper collectionRelationManyToManyCustomizer) 53: { 54: Type destinationEntityType = member.LocalMember.GetPropertyOrFieldType().GetGenericArguments().First(); 55: //set the mapping table column names from each source entity name plus the _Id sufix 56: collectionRelationManyToManyCustomizer.Column(destinationEntityType.Name + "_Id"); 57: } 58:  59: protected virtual new void BeforeMapSet(IModelInspector modelInspector, PropertyPath member, ISetPropertiesMapper propertyCustomizer) 60: { 61: if (modelInspector.IsManyToMany(member.LocalMember) == true) 62: { 63: propertyCustomizer.Key(x => x.Column(member.LocalMember.DeclaringType.Name + "_Id")); 64:  65: Type sourceType = member.LocalMember.DeclaringType; 66: Type destinationType = member.LocalMember.GetPropertyOrFieldType().GetGenericArguments().First(); 67: IEnumerable<String> names = new Type[] { sourceType, destinationType }.Select(x => x.Name).OrderBy(x => x); 68:  69: //set inverse on the relation of the alphabetically first entity name 70: propertyCustomizer.Inverse(sourceType.Name == names.First()); 71: //set mapping table name from the entity names in alphabetical order 72: propertyCustomizer.Table(String.Join("_", names)); 73: } 74: } 75: } Conclusion Of course, there is much more to mapping than this, I suggest you look at all the events and functions offered by the ModelMapper to see where you can hook for making it behave the way you want. If you need any help, just let me know!

    Read the article

  • Application not releasing database connection Spring.net + NHibernate

    - by anupam3m
    Even after successful transaction.Application connection with the database persist.in Nhibernate log it shows Nhibernate Log 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Impl.SessionImpl [(null)] <(null) - executing flush 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Impl.ConnectionManager [(null)] <(null) - registering flush begin 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Impl.ConnectionManager [(null)] <(null) - registering flush end 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Impl.SessionImpl [(null)] <(null) - post flush 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Impl.SessionImpl [(null)] <(null) - before transaction completion 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Impl.ConnectionManager [(null)] <(null) - aggressively releasing database connection 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Connection.ConnectionProvider [(null)] <(null) - Closing connection 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Impl.SessionImpl [(null)] <(null) - transaction completion 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Transaction.AdoTransaction [(null)] <(null) - running AdoTransaction.Dispose() 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Impl.SessionImpl [(null)] <(null) - closing session 2010-05-21 14:45:08,428 [Worker] [0] DEBUG NHibernate.Impl.BatcherImpl [(null)] <(null) - running BatcherImpl.Dispose(true) Underneath given is my dataconfiguration file -- Risco.Rsp.Ac.RMAC.Mapping Risco.Rsp.Ac.Logging.Appenders -- Please help me out with this issue.Thanks

    Read the article

  • Fluent NHibernate: Example of a one-to-many relationship on an abstract class of a table-per-subclas

    - by BigTommy79
    Hi All, I've been trying for ages to find an example (because I can't get it to work myself) of the correct mapping for a one-to-many relationship on an abstract class of a table-per-subclass implementation, in fluent nHibernate. An example below: I'm looking to map the list of Fines on the Debt abstract base class to the Fine class. if anyone knows of any tutorial or example they've come across before please let me know. Thanks, Tim public abstract class Entity { public int Id { get; set; } } public abstract class Debt : Entity { public decimal Balance { get; set; } public IList<Fine> Fines { get; set; } public Debt() { Fines = new List<Fine>(); } } public class CarLoan : Debt { } public class CreditCard : Debt { } public class LoanApplication : Entity { public IList<Debt> ExistingDebts { get; set; } public LoanApplication() { ExistingDebts = new List<Debt>(); } } public class Fine { public Int64 Cash { get; set; } }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >