Does anyone use nhibernate




















Similar to Entity Framework Core these methods are actually extension methods. I was hoping to keep NH out of my Domain project, but the cost of implementation seems quite high.

Pingback: No need for repositories and unit of work with Entity Framework Core. Good job Gunnar. NET Core loggers. Just wanted to stop by a say thank you for writing this article. Your email address will not be published. Notify me when new comments are added. Skip to content. NET Data platform.

SqlClient 4. NET Core 3. Generator Generators. Guid ; x. Type NHibernateUtil. Column "Id" ; x. UnsavedValue Guid. Length 50 ; x. StringClob ; x. AddMappings typeof NHibernateExtensions. AutoQuote; c. Validate; c. BuildSessionFactory ; services. AddSingleton sessionFactory ; services. OpenSession ; services. GetConnectionString "DefaultConnection" ; services. AddNHibernate connStr ; services. Injecting NHibernate to controllers We can now inject NHibernate mapper session to controllers and start querying for data.

StartsWith "How to". FirstOrDefaultAsync ; book. Following community best practices we can write the code above like shown here. Paging with NHibernate Paging is popular topic and I have previously written few blog posts about it. Skip skip. Take pageSize. StartsWith "B". Skip 1. Take 2. Wrapping up NHibernate has my warm welcome to. Liked this post? Empower your friends by sharing it!

You May Also Like. Assembly version tag helper for ASP. Handling missing tenants in ASP. Current version of EF Core 2. The next version 2. NHibernate can convert and query any type; EF Core still lacks this capacity, which should be introduced in the next version.

With NHibernate, you can already query spatial types, for example. Both of them have global filters at entity level. Easy to do soft deletes or multi-tenancy. Future versions will offer LINQ expression interception and lifetime events.

NHibernate has a very rich event and interception model. Both offer first-level caching of entities. NHibernate goes one step further, and has second-level caching using a distributed cache provider, such as these:. NHibernate can do validation using the companion project NHibernate Validator , or by implementing an interface this one has become somewhat legacy. EF Core uses Data Annotations validation , which is the de facto standard for doing validations in.

This is one aspect where EF is quite ahead of NHibernate, even though there have been attempts to create a similar framework for it. You can list all the versions of a schema, apply one explicitly or go back to a previous version.

It should come with time, of course. EF can generate entities from the database, and you can even modify the default behavior by registering your own version of infrastructure services. NHibernate has so many features that it is easy to forget about one. With NHibernate, one can map pretty much any database, so there is always an option.

EF Core is very easy to use, generally well documented, and this is something where NHibernate is far behind. As of now, it can only be used in relatively simple scenarios — just consider the lack of support for table inheritance strategies. Having a. NET Core version is essential to me. Having the possibility of supporting non-relational databases using the same familiar APIs and concepts is something very appealing to me, but yet to see working.

EF Core does have a roadmap, which is a good thing. Considering all the effort Microsoft is putting into it — plus the added contribution of the developer community — we can expect the best out of it. New releases seem to be coming at a steady pace, and we can take part in the decision process, even though Microsoft has the final word. For NHibernate, things are a bit worse. Currently the project is maintained by only a handful of developers, at most.

Things do seem to be moving, after some years of stagnation, and a good example is the port to. However, without professional developers working full time on this, it is reasonable to assume that progress will not be as fast as with EF — but NHibernate has the lead, in my opinion. The decision process is not so transparent, from where I sit. With APM, server health metrics, and error log integration, improve your application performance with Stackify Retrace.

Try your free two week trial today. Entity Framework Core Roadmap. NHibernate Milestones. Prefix: Supported. NET Core 2. Click here to read more about the acquisition. Try Our Free Code Profiler. Try Our Code Profiler. If not specified, the primary key of the associated class is used. This obsolete attribute also appears on other elements, with the same usage. Setting a value of the cascade attribute to any meaningful value other than none will propagate certain operations to the associated object.

The meaningful values are divided into three categories. The property-ref attribute should only be used for mapping legacy data where a foreign key refers to a unique key of the associated table other than the primary key.

This is a complicated and confusing relational model. For example, if the Product class had a unique serial number that is not the primary key, mapped as below:. Then the mapping for OrderItem might use:.

If the referenced unique key is the property of a component, you can specify a property path:. A one-to-one association to another persistent class is declared using a one-to-one element. This option affects the order in which Save and Delete are cascaded, and determines whether the association can be proxied.

It is also used by the schema export tool. If this is not the case, you can specify another column or expression to join on using an SQL formula. Primary key associations don't need an extra table column; if two rows are related by the association then the two table rows share the same primary key value. So if you want two objects to be related by a primary key association, you must make sure that they are assigned the same identifier value!

For a primary key association, add the following mappings to Employee and Person , respectively. We use a special NHibernate identifier generation strategy called foreign :. A newly saved instance of Person is then assigned the same primary key value as the Employee instance referred with the Employee property of that Person. Alternatively, a foreign key with a unique constraint, from Employee to Person , may be expressed as:.

And this association may be made bidirectional by adding the following to the Person mapping:. Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. NHibernate will generate the necessary unique key and nullability constraints, and your mapping will be more self-documenting.

We strongly recommend that you implement Equals and GetHashCode to compare the natural key properties of the entity. Components may, in turn, declare their own properties, components or collections. See Chapter 8, Component Mapping. For more informations, see lazy on property element. When a lazy property is accessed on an object, included when the property is a component, the other lazy properties of the lazy group are also loaded with it. When using dictionaries, the property names refer to keys of the dictionary.

See Section 8. The most important use of the construct is that it allows a combination of properties to be the target of a property-ref. It is also a convenient way to define a multi-column unique constraint. For example:. It is not an actual property name. It determines if a version increment should occur when these properties are dirty. You might have some legacy data association that refers to this unique key of the Person table, instead of to the primary key:.

The use of this outside the context of mapping legacy data is not recommended. Polymorphic persistence requires the declaration of each subclass of the root persistent class. NET class name of the subclass, including its assembly name. Each subclass should declare its own persistent properties and subclasses. Each subclass in a hierarchy must define a unique discriminator-value.

If none is specified, the fully qualified. NET class name is used. For information about inheritance mappings, see Chapter 9, Inheritance Mapping. Each subclass can also be mapped to its own table. This is called the table-per-subclass mapping strategy. An inherited state is retrieved by joining with the table of the superclass. No discriminator column is required for this mapping strategy. The mapping at the start of the chapter would be re-written as:.

A third option is to map only the concrete classes of an inheritance hierarchy to tables, the table-per-concrete-class strategy where each table defines all persistent state of the class, including inherited state.

In NHibernate, it is not absolutely necessary to explicitly map such inheritance hierarchies. However, if you wish use polymorphic associations e. This is useful if you want to have a view instead of a table. For example, the address information for a person can be mapped to a separate table while preserving value type semantics for all properties :.

This feature is often only useful for legacy data models, we recommend fewer tables than classes and a fine-grained domain model. However, it is useful for switching between inheritance mapping strategies in a single hierarchy, as explained later.

It appears anywhere the parent mapping element defines a join to a new table that references the primary key of the original table. It also defines the foreign key in the joined table:.

It is provided for legacy data. This is implied whenever the foreign key is also part of the primary key. This is implied whenever the foreign key is also the primary key.

Be aware that this feature bypasses NHibernate's usual optimistic locking strategy for versioned data. The not-null and update attributes are useful when mapping an unidirectional one-to-many association. Most of the attributes on column provide a means of tailoring the DDL during automatic schema generation. The column and formula elements can even be combined within the same property or association mapping to express, for example, exotic join conditions. Collections are discussed in Chapter 6, Collection Mapping.

Suppose your application has two persistent classes with the same name, and you don't want to specify the fully qualified name in NHibernate queries. You may even import classes and interfaces that are not explicitly mapped. NET class, including its assembly name. There is one more type of property mapping. This type of mapping requires more than one column. The first column contains the type of the associated entity. The remaining columns contain the identifier.

It is impossible to specify a foreign key constraint for this kind of association. This is not the usual way of mapping polymorphic associations and you should use this only in special cases. For example, for audit logs, user session data, etc. The meta-type attribute allows the application to specify a custom type that maps database column values to persistent classes that have identifier properties of the type specified by id-type.

If the meta-type is class , nothing else is required. The class full name will be persisted in the database as the type of the associated entity. On the other hand, if it is a basic type like int or char , you must specify the mapping from values to classes. Here is an example with string. String types are a special case: they can be used without meta-values, in which case they will behave much like the class meta-type.

It defines whether a version increment should occur if this property is dirty. To understand the behaviour of various. NET language-level objects with respect to the persistence service, we need to classify them into two groups:. An entity exists independently of any other objects holding references to the entity.

Contrast this with the usual. NET model where an unreferenced object is garbage collected. Entities must be explicitly saved and deleted except that saves and deletions may be cascaded from a parent entity to its children. This is different from the ODMG model of object persistence by reachability - and corresponds more closely to how application objects are usually used in large systems. Entities support circular and shared references.

They may also be versioned. An entity's persistent state consists of references to other entities and instances of value types.

Values are primitives, collections, components and certain immutable objects. Unlike entities, values in particular collections and components are persisted and deleted by reachability. Since value objects and primitives are persisted and deleted along with their containing entity they may not be independently versioned. Values have no independent identity, so they cannot be shared by two entities or collections. All NHibernate types except collections support null semantics if the.

NET type is nullable i. Up until now, we've been using the term "persistent class" to refer to entities. We will continue to do that. Strictly speaking, however, not all user-defined classes with persistent state are entities. A component is a user defined class with value semantics. The challenge is to map the.

The bridge between both systems is provided by NHibernate. The value of this attribute is the name of a NHibernate mapping type.

NHibernate provides a range of mappings for standard. Net value types out of the box. You can write your own mapping types and implement your own custom conversion strategies. The basic types may be roughly categorized into three groups - System. ValueType types, System. Object types, and System. Object types for large objects. Just like Columns for System. Otherwise null will be replaced by the default value for the type when reading, and then will be overwritten by it when persisting the entity, potentially leading to phantom updates.

Since NHibernate v5. DateTime2 is used instead of DbType. String types use by default. Net default string equality, which is case sensitive and culture insensitive. When a string type is used as an identifier, if the underlying database string equality semantic differs, it may cause issues. For example, loading a children collection by a string parent key stored in a case insensitive column may cause matching children having their parent key differing by the case to be ignored by NHibernate by default.

String types comparer can be set for matching the database or column behavior. To set the default comparer for all string types, affect by code a StringComparer to AbstractStringType. DefaultComparer static property. IgnoreCase : true for case insensitive comparisons.

Any other value will result in case sensitive comparisons. ComparerCulture : Current for using the application current culture, Invariant for using the invariant culture, Ordinal for using ordinal comparison, or any valid culture name for using another culture. By default, ordinal comparisons are used. These settings should be used in order to match the database or column behavior. They are not taken into account by the hbm2ddl tool for generating the database schema.

In other words, it will not generate matching collate statements for SQL-Server. NHibernate supports some additional type names for compatibility with Java's Hibernate useful for those coming over from Hibernate or using some of the tools to generate hbm. To see all of the conversions you can view the source of static constructor of the class NHibernate. Default NHibernate types used when no type attribute is specified can be overridden by using the NHibernate.

RegisterType static method before configuring and building session factories. It is relatively easy for developers to create their own value types. NHibernate does not provide a built-in type for this. But custom types are not limited to mapping a property or collection element to a single table column. To implement a custom type, implement either NHibernate. IUserType or NHibernate. ICompositeUserType and declare properties using the fully qualified name of the type.

Check out NHibernate. DoubleStringType to see the kind of things that are possible. The later is to be used with collections, see Section 6. You may even supply parameters to an IUserType in the mapping file. IParameterizedType interface.

The IUserType can now retrieve the value for the parameter named default from the IDictionary object passed to it. If you use a certain UserType very often, it may be useful to define a shorter name for it. Typedefs assign a name to a custom type, and may also contain a list of default parameter values if the type is parameterized.

It is also possible to override the parameters supplied in a typedef on a case-by-case basis by using type parameters on the property mapping. Even though NHibernate's rich range of built-in types and support for components means you will very rarely need to use a custom type, it is nevertheless considered good form to use custom types for non-entity classes that occur frequently in your application.

For example, a MonetaryAmount class is a good candidate for an ICompositeUserType , even though it could easily be mapped as a component. One motivation for this is abstraction.

With a custom type, your mapping documents would be future-proofed against possible changes in your way of representing monetary values. It is possible to provide more than one mapping for a particular persistent class.

In this case, you must specify an entity name to disambiguate between instances of the two mapped entities. By default, the entity name is the same as the class name.

NHibernate lets you specify the entity name when working with persistent objects, when writing queries, or when mapping associations to the named entity. Associations are now specified using entity-name instead of class. You may force NHibernate to quote an identifier in the generated SQL by enclosing the table or column name in back-ticks in the mapping document.

Quoting column identifiers is required if a table contains two columns differing only by case. Ensure you use consistent casing when quoting identifiers. It is possible to define subclass and joined-subclass mappings in separate mapping documents, directly beneath hibernate-mapping.

This allows you to extend a class hierarchy just by adding a new mapping file. You must specify an extends attribute in the subclass mapping, naming a previously mapped superclass. Generated properties are properties which have their values generated by the database. Typically, NHibernate applications needed to Refresh objects which contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to NHibernate.

Properties marked as generated must additionally be non-insertable and non-updatable. Only versions , timestamps , and simple properties can be marked as generated. Things like created-date would fall into this category. Note that even though version and timestamp properties can be marked as generated, this option is not available for them. In conjunction with NHibernate's schema evolution tools, they have the ability to fully define a user schema within the NHibernate mapping files.

Although designed specifically for creating and dropping things like triggers or stored procedures, any SQL command that can be run via a DbCommand. There are essentially two modes for defining auxiliary database objects:. This custom class must implement the NHibernate. IAuxiliaryDatabaseObject interface. SetParameterValues passing it a dictionary of parameter names and values. Additionally, these database objects can be optionally scoped such that they only apply when certain dialects are used.

You may declare additional metadata in your mappings by using the meta element. This element can be added to the main mapping elements. The metadata can be retrieved at runtime from the Section Chapter 5. Mapping declaration. XML Namespace. GUID Algorithms. Identity columns and Sequences. Assigned Identifiers.



0コメント

  • 1000 / 1000