Search Results

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

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

  • 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

  • What would be the equivalent VB.NET code for this C# FluentNHibernate component mapping?

    - by Will Marcouiller
    I'm a C# programmer constrained to write VB.NET code. While exploring NHibernate further for my current client, I encountered FluentNHibernate, which I find real attractive. But now, I wonder how to "translate" this C# code for component mapping into VB.NET code: Component(x => x.Address, m => { m.Map(x => x.Number); m.Map(x => x.Street); m.Map(x => x.PostCode); }); I know from here: Component(Of Client)(Function(c) c.Address, ...) what I miss is how to continue with the brackets in VB.NET, since there's no Begin End keywords or so. EDIT 1: Following Mr. JaredPar instructions, I figured that his solution might work. If we take the time to read his answer, we may notice that we both don't know what the MType is within his solution. I might have found out that the MType is: FluentNHibernate.Mapping.ComponentPart(Of TComponent) Thus, TComponent is, from my understanding, an anonymous type that I shall parameter to use. From this point of view, since I wish to map the properties of my Address object, replacing TComponent in my help method signature seems not to work. Private Sub MapAdresseHelper(Of Adresse)(ByVal a As FluentNHibernate.Mapping.ComponentPart(Of Adresse)) a.Map(Function(m) m.Number) a.Map(Function(m) m.Street).Length(50) a.Map(Function(m) m.PostCode).Length(10) End Sub The error I get is that my Address class doesn't have a property member named Street, for instance. It sees my Address type, it recognizes it, but it seems buggy somehow. I guess VBNET is poorly designed for lambda expressions and is less evolved than C# (Sorry, a bit of frustration due to the constraint of working with it and not being capable of doing things VERY easily done in C#.) Thanks!

    Read the article

  • Entity Association Mapping with Code First Part 1 : Mapping Complex Types

    - by mortezam
    Last week the CTP5 build of the new Entity Framework Code First has been released by data team at Microsoft. Entity Framework Code-First provides a pretty powerful code-centric way to work with the databases. When it comes to associations, it brings ultimate flexibility. I’m a big fan of the EF Code First approach and am planning to explain association mapping with code first in a series of blog posts and this one is dedicated to Complex Types. If you are new to Code First approach, you can find a great walkthrough here. In order to build a solid foundation for our discussion, we will start by learning about some of the core concepts around the relationship mapping.   What is Mapping?Mapping is the act of determining how objects and their relationships are persisted in permanent data storage, in our case, relational databases. What is Relationship mapping?A mapping that describes how to persist a relationship (association, aggregation, or composition) between two or more objects. Types of RelationshipsThere are two categories of object relationships that we need to be concerned with when mapping associations. The first category is based on multiplicity and it includes three types: One-to-one relationships: This is a relationship where the maximums of each of its multiplicities is one. One-to-many relationships: Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one. Many-to-many relationships: This is a relationship where the maximum of both multiplicities is greater than one. The second category is based on directionality and it contains two types: Uni-directional relationships: when an object knows about the object(s) it is related to but the other object(s) do not know of the original object. To put this in EF terminology, when a navigation property exists only on one of the association ends and not on the both. Bi-directional relationships: When the objects on both end of the relationship know of each other (i.e. a navigation property defined on both ends). How Object Relationships Are Implemented in POCO domain models?When the multiplicity is one (e.g. 0..1 or 1) the relationship is implemented by defining a navigation property that reference the other object (e.g. an Address property on User class). When the multiplicity is many (e.g. 0..*, 1..*) the relationship is implemented via an ICollection of the type of other object. How Relational Database Relationships Are Implemented? Relationships in relational databases are maintained through the use of Foreign Keys. A foreign key is a data attribute(s) that appears in one table and must be the primary key or other candidate key in another table. With a one-to-one relationship the foreign key needs to be implemented by one of the tables. To implement a one-to-many relationship we implement a foreign key from the “one table” to the “many table”. We could also choose to implement a one-to-many relationship via an associative table (aka Join table), effectively making it a many-to-many relationship. Introducing the ModelNow, let's review the model that we are going to use in order to implement Complex Type with Code First. It's a simple object model which consist of two classes: User and Address. Each user could have one billing address. The Address information of a User is modeled as a separate class as you can see in the UML model below: In object-modeling terms, this association is a kind of aggregation—a part-of relationship. Aggregation is a strong form of association; it has some additional semantics with regard to the lifecycle of objects. In this case, we have an even stronger form, composition, where the lifecycle of the part is fully dependent upon the lifecycle of the whole. Fine-grained domain models The motivation behind this design was to achieve Fine-grained domain models. In crude terms, fine-grained means “more classes than tables”. For example, a user may have both a billing address and a home address. In the database, you may have a single User table with the columns BillingStreet, BillingCity, and BillingPostalCode along with HomeStreet, HomeCity, and HomePostalCode. There are good reasons to use this somewhat denormalized relational model (performance, for one). In our object model, we can use the same approach, representing the two addresses as six string-valued properties of the User class. But it’s much better to model this using an Address class, where User has the BillingAddress and HomeAddress properties. This object model achieves improved cohesion and greater code reuse and is more understandable. Complex Types: Splitting a Table Across Multiple Types Back to our model, there is no difference between this composition and other weaker styles of association when it comes to the actual C# implementation. But in the context of ORM, there is a big difference: A composed class is often a candidate Complex Type. But C# has no concept of composition—a class or property can’t be marked as a composition. The only difference is the object identifier: a complex type has no individual identity (i.e. no AddressId defined on Address class) which make sense because when it comes to the database everything is going to be saved into one single table. How to implement a Complex Types with Code First Code First has a concept of Complex Type Discovery that works based on a set of Conventions. The convention is that if Code First discovers a class where a primary key cannot be inferred, and no primary key is registered through Data Annotations or the fluent API, then the type will be automatically registered as a complex type. Complex type detection also requires that the type does not have properties that reference entity types (i.e. all the properties must be scalar types) and is not referenced from a collection property on another type. Here is the implementation: public class User{    public int UserId { get; set; }    public string FirstName { get; set; }    public string LastName { get; set; }    public string Username { get; set; }    public Address Address { get; set; }} public class Address {     public string Street { get; set; }     public string City { get; set; }            public string PostalCode { get; set; }        }public class EntityMappingContext : DbContext {     public DbSet<User> Users { get; set; }        } With code first, this is all of the code we need to write to create a complex type, we do not need to configure any additional database schema mapping information through Data Annotations or the fluent API. Database SchemaThe mapping result for this object model is as follows: Limitations of this mappingThere are two important limitations to classes mapped as Complex Types: Shared references is not possible: The Address Complex Type doesn’t have its own database identity (primary key) and so can’t be referred to by any object other than the containing instance of User (e.g. a Shipping class that also needs to reference the same User Address). No elegant way to represent a null reference There is no elegant way to represent a null reference to an Address. When reading from database, EF Code First always initialize Address object even if values in all mapped columns of the complex type are null. This means that if you store a complex type object with all null property values, EF Code First returns a initialized complex type when the owning entity object is retrieved from the database. SummaryIn this post we learned about fine-grained domain models which complex type is just one example of it. Fine-grained is fully supported by EF Code First and is known as the most important requirement for a rich domain model. Complex type is usually the simplest way to represent one-to-one relationships and because the lifecycle is almost always dependent in such a case, it’s either an aggregation or a composition in UML. In the next posts we will revisit the same domain model and will learn about other ways to map a one-to-one association that does not have the limitations of the complex types. References ADO.NET team blog Mapping Objects to Relational Databases Java Persistence with Hibernate

    Read the article

  • How to create mapping for a List<SomeNativeType> in FluentNhibernate ?

    - by Mahesh Velaga
    Hi all, I am trying to create a mapping file for the following Model using Fluent NHibernate. But, I am not sure of how to do the mapping for the List in the mapping file. public class MyClass { public virtual Guid Id { get; set; } public virtual string Name { get; set; } public virtual List<string> MagicStrings { get; set; } } public class EnvironmentMapping : ClassMap<Models.Environment> { public EnvironmentMapping() { Id(x => x.Id); Map(x => x.Name); //HasMany(x => string) What should this be ? } } Help in this regard is much appreciated. Thanks!

    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

  • 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

  • Fluent Nhibernate - Mapping child in parent when Child has reference to parent and not using a list

    - by Josh
    I have a child object in the database that looks like this: CREATE TABLE Child ( ChildId uniqueidentifier not null, ParentId uniqueidentifier not null ) An then I have a parent like so. CREATE TABLE Parent ( ParentId uniqueidentifier not null ) Now, the problem is that in my Parent class, I have public virtual Child Child { get; set; } I've tried references, hasone, referencesany and can't seem to get the mapping right. Anyone have any ideas? Thanks,

    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

  • Mapping a collection of enums with NHibernate

    - by beaufabry
    Mapping a collection of enums with NHibernate Specifically, using Attributes for the mappings. Currently I have this working mapping the collection as type Int32 and NH seems to take care of it, but it's not exactly ideal. The error I receive is "Unable to determine type" when trying to map the collection as of the type of the enum I am trying to map. I found a post that said to define a class as public class CEnumType : EnumStringType { public CEnumType() : base(MyEnum) { } } and then map the enum as CEnumType, but this gives "CEnumType is not mapped" or something similar. So has anyone got experience doing this? So anyway, just a simple reference code snippet to give an example with [NHibernate.Mapping.Attributes.Class(Table = "OurClass")] public class CClass : CBaseObject { public enum EAction { do_action, do_other_action }; private IList<EAction> m_class_actions = new List<EAction>(); [NHibernate.Mapping.Attributes.Bag(0, Table = "ClassActions", Cascade="all", Fetch = CollectionFetchMode.Select, Lazy = false)] [NHibernate.Mapping.Attributes.Key(1, Column = "Class_ID")] [NHibernate.Mapping.Attributes.Element(2, Column = "EAction", Type = "Int32")] public virtual IList<EAction> Actions { get { return m_class_actions; } set { m_class_actions = value;} } } So, anyone got the correct attributes for me to map this collection of enums as actual enums? It would be really nice if they were stored in the db as strings instead of ints too but it's not completely necessary.

    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

  • nhibernate says 'mapping exception was unhandled' no persister for: MyNH.Domain.User

    - by mrblah
    Hi, I am using nHibernate and fluent. I created a User.cs: public class User { public virtual int Id { get; set; } public virtual string Username { get; set; } public virtual string Password { get; set; } public virtual string Email { get; set; } public virtual DateTime DateCreated { get; set; } public virtual DateTime DateModified { get; set; } } Then in my mappinds folder: public class UserMapping : ClassMap<User> { public UserMapping() { WithTable("ay_users"); Not.LazyLoad(); Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Username).Not.Nullable().WithLengthOf(256); Map(x => x.Password).Not.Nullable().WithLengthOf(256); Map(x => x.Email).Not.Nullable().WithLengthOf(100); Map(x => x.DateCreated).Not.Nullable(); Map(x => x.DateModified).Not.Nullable(); } } Using the repository pattern for the nhibernate blog: public class UserRepository : Repository<User> { } public class Repository<T> : IRepository<T> { public ISession Session { get { return SessionProvider.GetSession(); } } public T GetById(int id) { return Session.Get<T>(id); } public ICollection<T> FindAll() { return Session.CreateCriteria(typeof(T)).List<T>(); } public void Add(T product) { Session.Save(product); } public void Remove(T product) { Session.Delete(product); } } public interface IRepository<T> { T GetById(int id); ICollection<T> FindAll(); void Add(T entity); void Remove(T entity); } public class SessionProvider { private static Configuration configuration; private static ISessionFactory sessionFactory; public static Configuration Configuration { get { if (configuration == null) { configuration = new Configuration(); configuration.Configure(); configuration.AddAssembly(typeof(User).Assembly); } return configuration; } } public static ISessionFactory SessionFactory { get { if (sessionFactory == null) sessionFactory = Configuration.BuildSessionFactory(); return sessionFactory; } } private SessionProvider() { } public static ISession GetSession() { return SessionFactory.OpenSession(); } } My config: <?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.MsSql2005Dialect</property> <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> <property name="connection.connection_string">Server=.\SqlExpress;Initial Catalog=TestNH;User Id=dev;Password=123</property> <property name="show_sql">true</property> </session-factory> </hibernate-configuration> I created a console application to test the output: static void Main(string[] args) { Console.WriteLine("starting..."); UserRepository users = new UserRepository(); User user = users.GetById(1); Console.WriteLine("user is null: " + (null == user)); if(null != user) Console.WriteLine("User: " + user.Username); Console.WriteLine("ending..."); Console.ReadLine(); } Error: nhibernate says 'mapping exception was unhandled' no persister for: MyNH.Domain.User What could be the issue, I did do the mapping?

    Read the article

  • Fluent NHibernate Column Mapping with Reserved Word

    - by Josh Close
    I've read that using a back tick ` should allow for using of reserved words. I'm using SQL Server and Fluent NHibernate and have a column name "File". If I map it with "`File" it tries using [Fil] so it's adding the brackets correctly, but dropping the "e" from the end. If I map it as "`Filee" it uses [File] correctly. Am I doing something wrong or is this a bug in NHibernate or Fluent Nhibernate?

    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

  • How do you map a DateTime property to 2 varchar columns in the database with NHibernate (Fluent)?

    - by gabe
    I'm dealing with a legacy database that has date and time fields as char(8) columns (formatted yyyyMMdd and HH:mm:ss, respectively) in some of the tables. How can i map the 2 char columns to a single .NET DateTime property? I have tried the following, but i get a "can't access setter" error of course because DateTime Date and TimeOfDay properties are read-only: public class SweetPocoMannaFromHeaven { public virtual DateTime? FileCreationDateTime { get; set; } } . mapping.Component<DateTime?>(x => x.FileCreationDateTime, dt => { dt.Map(x => x.Value.Date, "file_creation_date"); dt.Map(x => x.Value.TimeOfDay, "file_creation_time"); }); I have also tried defining a IUserType for DateTime, but i can't figure it out. I've done a ton of googling for an answer, but i can't figure it out still. What is my best option to handle this stupid legacy database convention? A code example would be helpful since there's not much out for documentation on some of these more obscure scenarios.

    Read the article

  • How do I map to a parent or child in the same table with NHibernate?

    - by adolfojp
    Lets suppose that I have a Category table with a column that holds the id of a parent or child category from the same table. This design would allow me to have unlimited levels of Categories, or unlimited levels in a thread, for example. How can I map this relationship with NHibernate? Are there any disadvantages or warnings that I should take into consideration when doing this?

    Read the article

  • Hello NHibernate! Quickstart with NHibernate (Part 1)

    - by BobPalmer
    When I first learned NHibernate, I could best describe the experience as less of a learning curve and more like a learning cliff.  A large part of that was the availability of tutorials.  In this first of a series of articles, I will be taking a crack at providing people new to NHibernate the information they need to quickly ramp up with NHibernate. For the first article, I've decided to address the gap of just giving folks enough code to get started.  No UI, no fluff - just enough to connect to a database and do some basic CRUD operations.  In future articles, I will discuss a repository pattern for NHibernate, parent-child relationships, and other more advanced topics. You can find the entire article via this Google Docs link: http://docs.google.com/Doc?docid=0AUP-rKyyUMKhZGczejdxeHZfOGMydHNqdGc0&hl=en Enjoy! -Bob

    Read the article

  • Persisting simple tree with (Fluent-)NHibernate leads to System.InvalidCastException

    - by fudge
    Hi there, there seems to be a problem with recursive data structures and (Fluent-)NHibernate or its just me, being a complete moron... here's the tree: public class SimpleNode { public SimpleNode () { this.Children = new List<SimpleNode> (); } public virtual SimpleNode Parent { get; private set; } public virtual List<SimpleNode> Children { get; private set; } public virtual void setParent (SimpleNode parent) { parent.AddChild (this); Parent = parent; } public virtual void AddChild (SimpleNode child) { this.Children.Add (child); } public virtual void AddChildren (IEnumerable<SimpleNode> children) { foreach (var child in children) { AddChild (child); } } } the mapping: public class SimpleNodeEntity : ClassMap<SimpleNode> { public SimpleNodeEntity () { Id (x => x.Id); References (x => x.Parent).Nullable (); HasMany (x => x.Children).Not.LazyLoad ().Inverse ().Cascade.All ().KeyNullable (); } } now, whenever I try to save a node, I get this: System.InvalidCastException: Cannot cast from source type to destination type. at (wrapper dynamic-method) SimpleNode. (object,object[],NHibernate.Bytecode.Lightweight.SetterCallback) at NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues (object,object[]) at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer (object,object[]) My setup: Mono 2.8.1 (on OSX), NHibernate 2.1.2, FluentNHibernate 1.1.0

    Read the article

  • nhibernate configure and buildsessionfactory time

    - by davidsleeps
    Hi, I'm using Nhibernate as the OR/M tool for an asp.net application and the startup performance is really frustrating. Part of the problem is definitely me in my lack of understanding but I've tried a fair bit (understanding is definitely improving) and am still getting nowhere. Currently ANTS profiler has that the Configure() takes 13-18 seconds and the BuildSessionFActory() as taking about 5 seconds. From what i've read, these times might actually be pretty good, but they were generally talking about hundreds upon hundreds of mapped entities...this project only has 10. I've combined all the mapping files into a single hbm mapping file and this did improve things but only down to the times mentioned above... I guess, are there any "Traps for young players" that are regularly missed...obvious "I did this/have you enabled that/exclude file x/mark file y as z" etc... I'll try the serialize the configuration thing to avoid the Configure() stage, but I feel that part shouldn't be that long for that amount of entities and so would essentially be hiding a current problem... I will post source code or configuration if necessary, but I'm not sure what to put in really... thanks heaps! edit (more info) I'll also add that once this is completed, each page is extremely quick... configuration code- hibernate.cfg.xml <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" /> </configSections> <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_name">MyAppDEV</property> <property name="cache.provider_class">NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache</property> <property name="cache.use_second_level_cache">true</property> <property name="show_sql">false</property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property> <property name="current_session_context_class">managed_web</property> <mapping assembly="MyApp.Domain"/> </session-factory> </hibernate-configuration> </configuration> My SessionManager class which is bound and unbound in a HttpModule for each request Imports NHibernate Imports NHibernate.Cfg Public Class SessionManager Private ReadOnly _sessionFactory As ISessionFactory Public Shared ReadOnly Property SessionFactory() As ISessionFactory Get Return Instance._sessionFactory End Get End Property Private Function GetSessionFactory() As ISessionFactory Return _sessionFactory End Function Public Shared ReadOnly Property Instance() As SessionManager Get Return NestedSessionManager.theSessionManager End Get End Property Public Shared Function OpenSession() As ISession Return Instance.GetSessionFactory().OpenSession() End Function Public Shared ReadOnly Property CurrentSession() As ISession Get Return Instance.GetSessionFactory().GetCurrentSession() End Get End Property Private Sub New() Dim configuration As Configuration = New Configuration().Configure() _sessionFactory = configuration.BuildSessionFactory() End Sub Private Class NestedSessionManager Friend Shared ReadOnly theSessionManager As New SessionManager() End Class End Class edit 2 (log4net results) will post bits that have a portion of time between them and will cut out the rest... 2010-03-30 23:29:40,898 [4] INFO NHibernate.Cfg.Environment [(null)] - Using reflection optimizer 2010-03-30 23:29:42,481 [4] DEBUG NHibernate.Cfg.Configuration [(null)] - dialect=NHibernate.Dialect.MsSql2005Dialect ... 2010-03-30 23:29:42,501 [4] INFO NHibernate.Cfg.Configuration [(null)] - Mapping resource: MyApp.Domain.Mappings.hbm.xml 2010-03-30 23:29:43,342 [4] INFO NHibernate.Dialect.Dialect [(null)] - Using dialect: NHibernate.Dialect.MsSql2005Dialect 2010-03-30 23:29:50,462 [4] INFO NHibernate.Cfg.XmlHbmBinding.Binder [(null)] - Mapping class: ... 2010-03-30 23:29:51,353 [4] DEBUG NHibernate.Connection.DriverConnectionProvider [(null)] - Obtaining IDbConnection from Driver 2010-03-30 23:29:53,136 [4] DEBUG NHibernate.Connection.ConnectionProvider [(null)] - Closing connection

    Read the article

  • Need help with simple NHibernate mapping...

    - by mplarsen
    Need help with a simple NHibernate relationship... Tables/Classes Request ------- RequestId Title … Keywords ------- RequestID (key) Keyword (key) Request mapping file <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="CR.Model" assembly="CR"> <class name="CR.Model.Request, CR table="[dbo].[Request]" lazy="true"> <id name="Id" column="[RequestID]"> <generator class="native" /> </id> <property name="RequestorID" column="[RequestorID]" /> <property name="RequestorOther" column="[RequestorOther]" /> … Keyword?? </class> </hibernate-mapping> How do I simply map multiple keywords to a request? I don't need another mapping file for the keyword class, do I? It's be great if I could not only get the associated keywords, but add them too...

    Read the article

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