Use Code First EF's about, and some pit

Use Code First EF's about, and some pit

最近公司需要使用EF(Entity Framework)的CodeFirst,虽然之前接触过EF的使用,但是却从来  
没有使用过CodeFirst,所以便从网上和其他地方学习了一下,所以在此记录一下, 以便以后忘记  
的时候,可以回顾一下。

Introduction 1. Entity Framework's

Entity Framework是一种数据库的持久化框架,是微软开发的基于ADO.NET的ORM(Object   
Relational Mapping,对象关系映射)框架,它严格来说是由三种编程方式,第一种是 "DB First"  
,指的是数据库优先,根据数据库取映射实体,第二种是“Model First”指的是模型优先,根据模型  
取生成数据库中的表,第三种是“Code First”指的是代码优先,根据代码去生成数据库中的表,还有  
另外一种是来自数据库的“Code First”。

2.Code First of use

按照下面的操作安装EF的最新版本

Here Insert Picture Description
Then enter " install-Package Penalty for EntityFramework " command
Here Insert Picture Description
after the installation is successful, start writing the code
First, we first create several entities like "Student" and "SysClass", a student class class class, because class
is a reserved word in .net, so we named "SysClass" category for the class, but the "class" in the database is not a reserved word in what we can do multi-branded properties in the "SysClass" category ** [Table ( "class") ] **, and then in other fields Add on a few essential properties, there is a virtual on "SysClass" Students of property, indicate this is a foreign key.
Here Insert Picture Description
! [Insert Picture description here] (https://img-blog.csdnimg.cn/20190804113939982.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxODA5MTM3,size_16,color
And then create a "AccountContext" of this class inherits from "DBContext" (System.Data.Entity) This type of packaging and release of some of the configuration database, of course, the CRUD (CRUD) may be realized by this class. Parent class constructor implemented, parameters are passed nameof (AccountContext), which is specified in the database using the connection string, OnModelCreating () may override this method can not be rewritten, this method is mainly to indicate whether when the code is mapped to the database, whether to generate plural table, by default the name of the table is automatically generated plural.
Here Insert Picture Description
Then create a new "AccountInitialzer" class, used to initialize the database, he inherited from "DropCreateDatabaseIfModelChanges", it indicates that when an entity is changed, delete the database table, and then create a new database based on entity code mapping in the table and try its Seed write method, which
When the database is initialized, insert some test data, it also can be inherited DropCreateDatabaseAlways, but this method is relatively hard, every time deleted from the database table, in the code to rebuild the database, do not mind, it is required Note that this method Seek not run program will be executed, he was only the first to create the database will be executed, or when inconsistent entries in the database tables and code mapping, he will be executed.
Here Insert Picture Description
Finally, we begin configuring the database connection string name refers to the name of the database connection string is our "AccountContext" class incoming parameters, initial catalog is the name of the database was created, we here do not specify the location of the database was created, of course, Yes, he did not specify the location of the database will be created specify the file you created in the database folder in the new database, there is providerName = "System.Data.SqlClient" this must be put on, or it may be wrong.

Here Insert Picture Description
然后我们在指明我们需要使用的AccountContext 和AccountInitialzer ,向程序指明我们新建创建数据库时,需要使用的类。注意type里面配置的是程序集的名称,而不是命名空间的名称,还有就是disableDatabaseInitialization这个参数,false是指明启用这个配置,true这是禁用。
Here Insert Picture Description
然后我们在控制台继续敲代码,这里的Using语法,说明一下我们对DBcontext这个类查看定义发现,这个类是实现了IDisposable接口,这就意味着,它是可以被释放的托管资源,避免内存越占越多,造成的程序性能的较低,同时这也是一个好的编程习惯。
Here Insert Picture Description
运行程序后,我们发现程序运行正常
Here Insert Picture Description
我们在检查一下数据库,win+r 输入命令 ssms 打开数据库发现,数据库也被正常创建了,这里说明一下,这里除了生成了我们需要的表以外,还生成了表“dbo__MigrationHistory”,这个表是记录数据库迁移使用的,以后再做说明,每次数据库表结构的更新,都会在这里存下数据。

Here Insert Picture Description
这样我们的Code First就完成了。

3.EF的一些坑

看了上面的文章是不是觉得CodeFirst还是很简单的,通过是用EF 我们甚至不再需要学习数据库的一些知识,甚至可以让我们不再关心数据库内部的实现,只需要我们修改代码,便可以修改掉数据库中的表结构,Code First用的好,我们甚至都不必去打开一次数据库。但是EF看着好用,其实它内部的坑或者或一些比较让人忽略的东西还是有不少的。
我们重新改造一下控制台的代码,添加 context.Database.Log +=c=> Console.WriteLine©; 这句话会帮我们记录数据的日志。
Here Insert Picture Description
我们执行查询操作 发现控制台多了许多代码,这就是数据库的日志,当然,我们看到的这条sql语句,就是我们执行 var student = context.Student.Find(1); 这句话时,生成的sql语句,是不是用起来很方便,但是我们只需要查询主键是1的数据,他却给我们生成了这么长的一条sql语句,是不是看起来感觉EF其实也笨笨的,所以这就是EF不适合大型项目的原因。
Here Insert Picture Description
EF的缓存机制:
我们输入这样的代码,两次查询主键是1的学生
Here Insert Picture Description
我们查看日志,发现只生成了一条sql。
Here Insert Picture Description
我们再次修改代码,我们都只是查询主键是1的学生,只不过是换了一种方式,我们在查看日志。
Here Insert Picture Description
这里我们发现,它生成了两条相同的sql
Here Insert Picture Description
这里我们发现,find会优先去缓存中去查询数据,而where则会每次都会生成新的sql去执行查询,就算查询条件相同,where也会生成新的sql。所以where可以保证我们每次都能取到最新的数据,而find则不行,之所以出现这种情况,我是这么理解的,find查询的数据的每次都只能返回一条,数据量小,不会占用太多的内存,但是where我们发现返回的是IQueryable类型的数据,这样就不能保证返回的数据量小了,因此为了性能的这个就不会放到缓存中去了。
Attach的使用
我们修改一下代码:
Here Insert Picture Description
我们先查询一个学生,然后在修改它的Name属性,然后保存,这里result返回的是0,意思是没有执行成功,我们查看数据库发现确实没有修改成功。这里就要说明一下了,这里我们使用的是两个AccountContext对象,context对象查询出了学生student,context对象便开始监管这个对象,我们用context1这个对象修改是,因为context1这个对象,根本就不知道student是谁,当然会修改失败了。这样我们在修改一下代码:
Here Insert Picture Description
我们发现返回的是1,当在查看数据库时,发现数据库的信息被修改了。Attach是将查出来的student让context1进行监管,就相当于与这个student对象是被context1查出来的一样,但也是有区别的,所以我们就修改成功了。需要注意的是如果被修改的对象的属性在Attach之前,会修改失败的,因为那时候,context1还没有对student进行监管。
比如这样,就会修改失败,
Here Insert Picture Description
按需修改
EF是支持按需修改的,我们修改代码:
Here Insert Picture Description
查看日志,发现只修改了Name属性,
Here Insert Picture Description
AsNoTracking的使用
Once again, we modify the code
Here Insert Picture Description
we added AsNoTracking in the query to the data () method, once again modify entity finding revision failed to explain here what AsNoTracking () This method, he said no longer tracking this data, which is the context of this object no regulatory oldstudent this object, it will amend failure, although you can improve performance to a certain extent, but do not use the mind.
Well, this article will stop here. Later introduce other intellectual point of EF.

Published 13 original articles · won praise 2 · Views 506

Guess you like

Origin blog.csdn.net/qq_41809137/article/details/98464525