Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between LINQ to SQL and NHibernate

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what's the difference between LINQ to SQL and NHibernate". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what's the difference between LINQ to SQL and NHibernate"?

1 introduction

When developing a system that deals with databases, the most tedious thing is to use ADO.NET to operate the background database without programming pleasure, because all database connections, reads and operations are the same, and programming becomes manual work.

Although we can design our own classes as the persistence layer for database access, each class must have different SQL statements, which makes it very difficult to design unified database read and write classes.

In this case, developers must arrange the process of form design, method design, database read-write design, which not only increases the burden of developers, but also makes the maintenance and later development of the project difficult.

2. ORM solution under. Net

2.1 LINQ

2.1.1 introduction to LINQ

As a query scheme developed by Microsoft, LINQ provides a more general way to add some general-purpose syntax query features (query facilities) to .net Framework that can be applied to all information sources (all sources of information). This is a better way than adding some relational data (relational) features or similar XML features (XML-specific) to the development language and runtime (runtime). These grammatical features are called the .NET Language Integrated Query (LINQ).

If you think the above explanation is a bit abstract, then it can be understood that LINQ actually provides a set of query functions that can query any data source, where the data source does not only refer to the database or XML files, but any collection or entity, such as the array that we need to use in various programming languages, now we do not have to traverse the array elements to find the items we need, LINQ can achieve this query.

LINQ query array:

Figure 2.1 LINQ query array

The above is the simplest LINQ implementation to query the array. The generic type var provides powerful delegate type support in the LINQ query. Regardless of the type of items in the query collection (whether int,char or string or class), we can save the results of the LINQ query with only one var. The results of the program are as follows:

Figure 2.2 LINQ query array program results

Is it very convenient? the application of LINQ is far from these. Through different mapping schemes, we can access the database (LINQ To SQL) and the XML file (LINQ To XML).

2.1.2 introduction to LINQ

Table 2.1 operators for LINQ

Operator

Description

Polymerization

Aggregate

Execute a custom method on the sequence

Average

Calculate the average value of a numerical sequence

Count

Returns the number of items in the sequence (integers)

LongCount

Returns the number of items in the sequence (long)

Min

Find the minimum number in a sequence of numbers

Max

Find the number of * in a sequence of numbers

Sum

Summarize the numbers in the sequence

Connect

Concat

Join two sequences into one sequence

Conversion

Cast

Converts elements in a sequence to a specified type

OfType

Filter elements of the specified type in the sequence

ToArray

Returns an array from a sequence

ToDictionary

Returns a dictionary from a sequence

ToList

Returns a list from a sequence

ToLookup

Returns a query from a sequence

ToSequence

Returns an IEnumerable sequence

element

DefaultIfEmpty

Create a default element for an empty sequence

ElementAt

Returns the elements of the specified index in the sequence

ElementAtOrDefault

Returns the elements of the specified index in the sequence, or the default value if the index is out of range

First

Returns * elements in the sequence

FirstOrDefault

Returns the * elements in the sequence, or the default value if no elements are found

Last

Returns an element in the sequence

LastOrDefault

Returns an element in the sequence or, if no element is found, the default value

Single

Returns a single element in a sequence

SingleOrDefault

Returns a single element in the sequence, or returns the default value if the element is not found

Equal

SequenceEqual

Compare two sequences to see if they are equal

Generate

Empty

Generate an empty sequence

Range

Generate a sequence with a specified range

Repeat

Generate a sequence by repeating a project a specified number of times

Grouping

GroupBy

Group the items in the sequence according to the specified grouping method

Connection

GroupJoin

Join two sequences together by grouping

Join

Join two sequences from the inside

Sort

OrderBy

Sort by value in ascending order

OrderByDescending

Sort by value in descending order

ThenBy

Sort the sorted sequence in ascending order

ThenByDescending

Sort the sorted sequence in descending order

Reverse

Reverse the order of items in a sequence

Zoning

Skip

Returns a sequence that skips a specified number of items

SkipWhile

Returns the sequence that skips items that do not satisfy the expression

Take

Returns a sequence with a specified number of items

TakeWhile

Returns a sequence with items that satisfy the expression

Projection

Select

Create a projection of a partial sequence

SelectMany

Create one-to-many projections of partial sequences

Qualifier

All

Determine whether all items in the sequence meet a condition

Any

Determine if any items in the sequence meet the criteria

Contains

Determines whether the sequence contains the specified item

Limit

Where

Filter items in a sequence

Set up

Distinct

Returns a sequence of non-duplicate items

Except

Returns a sequence that represents the difference between two sequences

Intersect

Returns a sequence that represents the intersection of two sequences

Union

Returns a sequence that represents the intersection of two sequences

Lambda expression

Many standard query operators use Func delegates to process individual elements when performing operations on a sequence. Lambda expressions can be used in conjunction with standard query operators to represent delegates. The lambda expression is an abbreviated expression for creating a delegate implementation and can be used in all situations where anonymous delegates apply. Both C # and Visual Basic ®.NET support Lambda expressions. However, it is important to note that because Visual Basic .NET does not yet support anonymous methods, Lambda expressions may contain only one statement.

The program in the above example is equivalent to the following

Figure 2.3 use of Lambda expressions

2.2 NHibernate

When it comes to NHibernate, we have to mention Hibernate for the simple reason that Hibernate is the .NET version of Hibernate.

Hibernate is an open source object-relational mapping framework, which encapsulates JDBC with very lightweight objects, so that Java programmers can use object programming thinking to manipulate the database at will. Hibernate can be used in any situation where JDBC is used, not only in Java client programs, but also in Servlet/JSP Web applications. * Revolutionary significance is that Hibernate can replace CMP in the J2EE architecture of EJB to complete the important task of data persistence.

The implementation of NHibernate as the .NET of Hibernate is exactly the same as that of Hibernate, and you can learn Hibernate materials directly by learning NHibernate.

In fact, although Hibernate is the most widely used solution in the field of Java database mapping, NHibernate is much colder in .NET due to the use of mapping schemes such as LINQ (including Microsoft's next-generation heavyweight Entity Framework).

NHibernate needs to configure database configuration files and class / table mapping configuration files, so using NHibernate requires a basic knowledge of XML files, as well as a more complex XML file configuration section and corresponding configuration commands.

2.2.1 Database profile

NHibernate officially provides templates and examples of configuration files for our reference.

Figure 2.4 NHibernate official database profile template (corresponding to different databases)

The image above shows the database configuration file. Usually suffixed with "cfg.xml", the contents of an example file are as follows

Figure 2.5 sample database configuration file

Here are some other configurations that can change the NHibernate behavior at run time. All of these are optional and have reasonable default values.

Table 2.2 NHibernate configuration Properties

Attribute name

Use

Hibernate.dialect

Class name of NHibernate dialect (Dialect)-allows NHibernate to use the features of certain database platforms

For example: full.classname.of.Dialect (if the dialect is created in NHibernate), or full.classname.of.Dialect, assembly (if you use an implementation of a custom dialect, it does not belong to NHibernate).

Hibernate.default_schema

In the generated SQL, the fully qualified name of scheml/tablespace.

For example: SCHEMA_NAME

Hibernate.prepare_sql

Whether or not to prepare sql statements

For example: true | false

Hibernate.session_factory_name

SessionFactory is automatically bound to this name when it is created.

For example: some.name

Hibernate.use_outer_join

Allows the use of external connection fetching.

For example: true | false

Hibernate.cache.provider_class

Specify the class name of a custom CacheProvider cache provider

For example: full.classname.of.CacheProvider (if ICacheProvider is created in NHibernate), or full.classname.of.CacheProvider, assembly (if you use a custom ICacheProvider, it does not belong to NHibernate).

Hibernate.query.substitutions

Replace some phrases in the NHibernate query with SQL phrases (for example, phrases may be functions or characters).

For example: hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC

2.2.2 entity Mapping profile

An example of an entity mapping configuration file is provided in the official NHibernate open source package for our reference.

Figure 2.6 entity mapping configuration file provided in the NHibernate open source package

Like the database configuration file, the entity mapping configuration file is also a XML file (XML is really powerful, Microsoft's next-generation application development technology WPF is to use XML files to unify the long-term separation of Cmax S and Bhand S under one roof), except that the entity mapping configuration file suffix is "hbm.xml".

Figure 2.7 entity Mapping profile

The information to be configured by the entity mapping profile is generally

Dead Schema

All XML mappings need to use nhibernate-mapping-2.0 schema. The current schema can be found in the resource path of NHibernate or in the embedded resource (Embedded Resource) of NHibernate.dll. NHibernate always gives priority to schema files embedded in resources.

Dead hibernate-mapping

(1)

Schema (optional): database schema name.

(2)

Default-cascade (optional-default is none): default cascading style.

(3)

Auto-import (optional-default is true): specifies whether we can use non-fully qualified class names in the query language (only for classes in this mapping file).

(4)

Default-access (optional-default is property): policy when NHibernate accesses property values.

(5)

Assembly (optional): specify an assembly that will be used if it is not specified in the mapping document.

(6)

Namespace (optional): specify a namespace prefix that is used if the fully qualified name is not specified in the mapping document.

Dead class

(1)

Name: the fully qualified name of the persistent class (or interface).

(2)

Table: the corresponding database table name.

(3)

Discriminator-value (optional-the default is the same as the class name): a value used to distinguish between different subclasses, used in polymorphic behavior.

(4)

Mutable (optional, default is true): indicates that the instance of this class is mutable (immutable).

(5)

Schema (optional): overrides the schema name specified in the root element.

(6)

Proxy (optional): specifies an interface to be used as a proxy in case of delayed loading. You can use the class's own name here.

(7)

Dynamic-update (optional, default is false): specifies that the SQL for UPDATE will be generated dynamically at run time, and only those fields that have been changed will be updated.

(8)

Dynamic-insert (optional, default is false): specifies that the SQL for INSERT will be generated dynamically at run time and contains only those non-null value fields.

(9)

Polymorphism (optional, default is implicit (implicit)): defines whether to use query polymorphism implicitly or explicitly.

(10)

Where (optional) specifies an additional SQL WHERE condition that is always added when fetching objects of this class.

(11)

Persister (optional): specify a custom IClassPersister.

(12)

Lazy (optional): if you set lazy= "true", you will set the name of the class itself as an equivalent shortcut form of the proxy interface.

Dead id

(1)

Name (optional): identifies the name of the attribute.

(2)

Type (optional): a name that identifies the NHibernate type.

(3)

Column (optional-default is the property name): the name of the primary key field.

(4)

Unsaved-value (optional-default is null): a specific identity attribute value that indicates that the instance has just been created and has not been saved. This distinguishes such instances from those that have been loaded from previous session but have not been persisted again.

(5)

Access (optional-default is property): the policy that NHibernate uses to access attribute values.

In addition, we can learn more about configuration through other ways, a NHibernate project, configuration file errors often lead to wrong results or even make the program unable to run.

Thank you for reading, the above is the content of "what is the difference between LINQ to SQL and NHibernate". After the study of this article, I believe you have a deeper understanding of the difference between LINQ to SQL and NHibernate, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report