[ORM] Entity Framework (2) CodeFirst advanced, ormcodefirst

Source: Internet
Author: User

[ORM] Entity Framework (2) CodeFirst advanced, ormcodefirst

In the previous section, we implemented CodeFirst quick start. However, many database details cannot be customized. Notes for using EF.

In this section, the following

  • Connection string in EF
  • EF object status
  • Delayed loading. Why Virtual and greedy loading?
  • Direct SQL query by bypassing EF
  • View SQL statements generated by EF
  • The ing between entities and databases is implemented through DataAnnotation and FluentAPI.
  • A crud example using the MVC asynchronous Controller
  • Suggestions

 

Connection string

1 complete connection string IP: Port \ Instance name database name Composition

After Nuget is installed, EF is added under the *. config entityFramework node, indicating that the LocalDb database is used and the Instance name is v11.0.

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">      <parameters>        <parameter value="v11.0" />      </parameters></defaultConnectionFactory>

The database name is the fully qualified name of the class by default. The following calls the parent class constructor, indicating that the database name is SaleDb. Instead of namespace + class name.

    public class SaleDb : DbContext    {        public SaleDb():base("SaleDb")        {              }    }

Of course, you can write the complete connection string in this constructor.

 

EF object status

Db. Entry (TEntity). State (append Entity and set status)

Public enum EntityState {// Summary: // The entity is not being tracked by the context. an entity is in this state // immediately after it has been created with the new operator or with one of // the System. data. entity. dbSet Create methods. detached = 1, // Summary: // The entity is being tracked by the context and exists in the database, and // its property values have not changed from the values in the database. unchanged = 2, // Summary: // The entity is being tracked by the context but does not yet exist in the/database. added = 4, // Summary: // The entity is being tracked by the context and exists in the database, but // has been marked for deletion from the database the next time SaveChanges // is called. deleted = 8, // Summary: // The entity is being tracked by the context and exists in the database, and // some or all of its property values have been modified. modified = 16 ,}

  

Delayed loading, greedy loading, Why Virtual

Lazy load (also called lazy load) is proposed to avoid unnecessary performance overhead, the so-called delayed loading means that data loading is performed only when data is actually needed. It can be simply understood that an SQL statement is issued for query only when it is used.

Greedy loading means loading the relevant tables at one time.

In EF, delayed loading is supported by default.

Db. Configuration. LazyLoadingEnabled = false; // you can disable delayed loading.

To load a single table greedily. Use Include ("table name ")

Db. Orders. Include ("OrderItems"); // load the OrderItems table together.

 

Virtual keywords

The Virtual keyword modifier is usually used when the connected table is used as the Entity attribute. If the Virtual keyword is not added, the associated class is only a common POCO type. Get, set method is empty implement.

After the Virtual keyword is used, EF generates a proxy class to override the get and set methods. Implement the required functions.

  

Direct SQL query by bypassing EF

As a framework, EF cannot meet all requirements. EF provides direct operations on Ado.net.

Three APIs are supported:

  • DbContext. Database. ExecuteSqlCommand
  • DbContext. Database. SqlQuery
  • DbSet. SqlQuery

         

Run the SQL statement to return the affected function.

public int ExecuteSqlCommand(string sql, params object[] parameters); 

 

Execute the SQL statement to return the query result and automatically map it to the specified class. (Not tracked by EF)

DbRawSqlQuery<TElement> SqlQuery<TElement>(string sql, params object[] parameters);

 

Execute the SQL statement to return the query result and automatically map it to the specified class. (The status is tracked by EF. DbSqlQuery inherited from DbRawSqlQuery)

virtual DbSqlQuery<TEntity> SqlQuery(string sql, params object[] parameters);

 

View SQL statements generated by EF

When using EF to execute a complex query. We need to know whether EF is executed as required. In this case, you need to view the statements generated by EF.

 

DataAnnotation

The DataAnnotation feature is introduced in. NET 3.5, providing a method for adding verification to classes in. NET. At the same time, EF is also a way to add constraints and Customize settings.

The following features are commonly used.

    public class Order    {        [Key]        public int Id { get; set; }        [StringLength(200)]        public string Name { get; set; }        public int UserId { get; set; }        [ForeignKey("UserId")]        public User User { get; set; }        public virtual ICollection<OrderItem> OrderItems { get; set; }    }

  

 

FluentAPI

DataAnnotation (DA) is very convenient, but sometimes our POCO class does not want to be directly associated with EF. Or DA cannot meet the requirement. In this case, we can use FluentAPI.

        protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            modelBuilder.Entity<AppInfo>().Property(o => o.Id).HasColumnName("AppId");        }

  

A crud example of MVC asynchronous Controller

It is always so convenient for Microsoft to associate its own things.

In MVC5, EF is used to automatically generate the controller.

 

 

Suggestions

1. The database is regenerated due to model changes, resulting in table data loss.

In CodeFirst, when the model changes, the data is not cleared using the EF Migration API in Nuget in section 1.

2. Whether to use stored procedures to view these database technologies.

When using the ORM framework such as EF, we should focus on the database technology and business logic layer. My suggestion is not to use stored procedures. The view actually only stores SQL statements.

 

MVC5 code download: MVCTest

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.