C #: entity framework EF (entity framework)

1, What is the Entity Framework

The ORM tool officially provided by Microsoft allows developers to save code time for database access and put more time on business logic layer code. EF provides change tracking, uniqueness constraints, lazy loading, query things, etc. Developers use Linq language to operate the database as easily as Object objects. EF has three usage scenarios: 1. Generate Class from database, 2. Generate database table structure from entity Class, 3. Design database through database visual designer and generate entity Class at the same time.

 

What is O/RM?

ORM   Is a tool for automatically mapping data stores from domain objects to relational databases. ORM mainly includes three parts: domain object, relational database object and mapping relationship. ORM classes provide automated CRUD, freeing developers from database API s and SQL.

2, Entity   Framework   framework

 

 

 

EDM   (entity data model): EDM includes three models: conceptual model   Map and store models.

conceptual model  ︰  The conceptual model contains model classes and the relationships between them. Design independent of database tables.

Storage model  ︰  Storage model is a database design model, including tables   View   Stored procedures and their relationships and keys.

mapping  ︰  Mapping contains information about how to map a conceptual model to a storage model.

LINQ to Entities ︰   LINQ to Entities   Is a query language for writing queries against object models. It returns the entities defined in the conceptual model.

Entity   SQL:   Entity   SQL is another language similar to L2E, but it is much more complex than L2E, so developers have to learn it alone.

Object services: it is the access portal of the database, which is responsible for data materialization, from client entity data to database records, and from database records to entity data.

Entity   Client   Data   Provider: its main responsibility is to convert L2E or Entity Sql into Sql query statements that can be recognized by the database. It uses Ado .NET Communication sends data to the database to obtain data.

ADO.Net   Data   Provider: uses standard Ado.net to communicate with the database

3, Entity Framework running environment

EF5 consists of two parts, EF api and. net framework 4.0/4.5, while EF6 is an independent EntityFramework.dll and does not depend on. net Framework. Use NuGet to install EF.

 

 

  4, Create entity data model

Use the wizard to create entity classes, or key add, fool~

 

 

 

After adding, the following configuration will be added to the. config file

<?xmlversion="1.0"?><configuration><configSections><!-- For more information on Entity Framework configuration, visit http://Go.microsoft.com/fwlink/?LinkID=237468 --><sectionname="entityFramework"type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"requirePermission="false"/></configSections><startup><supportedRuntimeversion="v4.0"sku=".NETFramework,Version=v4.5"/></startup><entityFramework><defaultConnectionFactorytype="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/><providers><providerinvariantName="System.Data.SqlClient"type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/></providers></entityFramework><connectionStrings><addname="SchoolDBEntities"connectionString="metadata=res://*/SchoolDB.csdl|res://*/SchoolDB.ssdl|res://*/SchoolDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\sqlexpress;initial catalog=SchoolDB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;"providerName="System.Data.EntityClient"/></connectionStrings></configuration>

Context  &  Entity   Class:

Each Entity Data Model generates a context class, and each database table generates an entity class. For example, two important files {EDM Name}.context.tt and {EDM Name}.tt contained in School.edmx:

 

 

 

School.Context.tt: the T4 template is used to generate the context class. You can see from the directory structure that School.Context.tt contains a School.Context.cs file.

School.tt: Entity class used to generate table mappings. The Entity class is a POCO class. Such as Student generation

publicpartialclassStudent

{

public Student()

{

this.Courses = new HashSet<Course>();

}

 

publicint StudentID { get; set; }

publicstring StudentName { get; set; }

publicNullable<int> StandardId { get; set; }

publicbyte[] RowVersion { get; set; }

 

publicvirtualStandard Standard { get; set; }

publicvirtualStudentAddress StudentAddress { get; set; }

publicvirtualICollection<Course> Courses { get; set; }

}

 

  5, Template browser

Take SchoolDB as an example. Switch to the Model View and see the class diagram structure:

 

 

  6, DBContext

 

  In Section 4, it is mentioned that EDM generates the SchoolDBEntities class, which inherits from the System.Data.Entity.DbContext class. The Context class in entityframework 4.1 inherits from the ObjectContext class. DbContext class is similar to ObjectContext. It wraps ObjcetContext class. There are three modes that are more conducive to development: CodeFirst, Model First and Database First

 

    DbContext is a very important part of the EntityFramework. It is a bridge between the domain model and the database. It is the main class to communicate with the database.

 

 

 

DbContext is mainly responsible for the following activities:

EntitySet: DbContext contains all entities mapped to the table

Querying: Translate LINQ to entities into Sql and send it to the database

Change Tracking: retain and track entity data changes after obtaining entities from the database

Persisting Data: execute the Insert, update, and delete commands according to the entity status

Caching: the default first level cache of DbContext, which stores entity in the lifecycle of the context

Manage Relationship: DbContext uses CSDL, MSL and SSDL to manage object relationships in DbFirst mode, and fluent in Code first   api management relationship

Object Materialization: DbContext converts a physical table into an entity instance object

DEMO

DbContext instantiation:

using (var ctx = newSchoolDBEntities())
{
//Can perform CRUD operation using ctx here..
}
take DbContext Turn into ObjectContext

using (var ctx = newSchoolDBEntities())
{
var objectContext = (ctx as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext;
//use objectContext here..
}

7, Entity   Entity type in Framework

POCO Entity (Plain Old CLR Object):

Classes that do not depend on any Framework classes (also   known   as   persistence-ignorant   objects) to generate CRUD command services for the Entity Data Model.

public class Student
{

public Student()

    {

this.Courses = new List<Course>();

    }

public int StudentID { get; set; }

public string StudentName { get; set; }

public Nullable<int> StandardId { get; set; }

public Standard Standard { get; set; }

public StudentAddress StudentAddress { get; set; }

public IList<Course> Courses { get; set; }

}

 

Dynamic Proxy (POCO Proxy):

    Dynamic Proxy is the proxy class of POCO class at runtime, which is similar to the wrapper of POCO class. Dynamic Proxy allows Lazy loading and automatically tracks changes. POCO Entity can be converted to POCO Proxy only if the following points are met:

1. It must be declared as public class

2. Cannot be sealed

3. It cannot be an abstract class

4. The Navigation attribute must be public and virtual (entity contains two attributes, Scalar attribute and Scalar attribute)   properties: the field value of the entity itself, Navigation   properties: references to other entities (such as class student)

5. Set attribute must be   ICollection<T>

six   ProxyCreationEnabled option must be true

public class Student

{

public Student()

{

this.Courses = new HashSet<Course>();

}

 

public int StudentID { get; set; }

public string StudentName { get; set; }

public Nullable<int> StandardId { get; set; }

 

public virtual Standard Standard { get; set; }

public virtual StudentAddress StudentAddress { get; set; }

public virtual ICollection<Course> Courses { get; set; }

}

  8, Entity   Relationships:

 

  IX   Entity   Lifecycle

When we do CRUD operations, we should first understand how the EntityFramework manages entity state. During the life cycle of each entity, a state will be saved in the DbContext, which is

Added Deleted Modified Unchanged Detached

 

  10, Code First, DBFirst, Model First

During the design of CodeFirst domain, the entity class is defined first, and the database is generated with the entity class

DbFirst generates entity classes from the database

Model First uses Visual Studio Entity designer to design ER and generate Entity class and DB at the same time

 

  11, Use query

Three query methods 1)   LINQ   to   Entities,   2)   Entity   SQL,   and   3)   Native   SQL

LINQ to Entities:

LINQ Method syntax:

//Querying with LINQ to Entities 

using (var context = newSchoolDBEntities())
{

    var L2EQuery = context.Students.where(s => s.StudentName == "Bill");

    var student = L2EQuery.FirstOrDefault<Student>();

}

 

LINQ Query syntax:

using (var context = new SchoolDBEntities())
{

    var L2EQuery = from st in context.Students

    where st.StudentName == "Bill"select st;

    var student = L2EQuery.FirstOrDefault<Student>();

}

 

Entity SQL:

//Querying with Object Services and Entity SQL

string sqlString = "SELECT VALUE st FROM SchoolDBEntities.Students " +

"AS st WHERE st.StudentName == 'Bill'";

 

var objctx = (ctx as IObjectContextAdapter).ObjectContext;

 

ObjectQuery<Student> student = objctx.CreateQuery<Student>(sqlString);

Student newStudent = student.First<Student>();

//Using EntityDataReader

using (var con = newEntityConnection("name=SchoolDBEntities"))

{

con.Open();

EntityCommand cmd = con.CreateCommand();

cmd.CommandText = "SELECT VALUE st FROM SchoolDBEntities.Students as st where st.StudentName='Bill'";

Dictionary<int, string> dict = newDictionary<int, string>();

using (EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))

{

while (rdr.Read())

{

int a = rdr.GetInt32(0);

var b = rdr.GetString(1);

dict.Add(a, b);

}

}

}

Native SQL:

using (var ctx = newSchoolDBEntities())
{

    var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student where studentname='Bill'").FirstOrDefault<Student>();

}

  12, Tracking change and persistence scenarios

Persistent in connected state and offline state

Persistent in the connected state. In the same DbContext, you do not need to destroy the Entity and write it directly to the database

 

  Offline state persistence refers to reading and saving an Entity in two different dbcontexts. Context2 does not know the update state of the Entity, so context2 must be notified of the update of the current Entity.

 

 

Context only tracks additions and deletions on the DbSet

Correct addition and deletion

using (var context = new SchoolDBEntities())

{

var studentList = context.Students.ToList<Student>();

//Perform create operation

context.Students.Add(newStudent() { StudentName = "New Student" });

//Perform Update operationStudent studentToUpdate = studentList.Where(s => s.StudentName == "student1").FirstOrDefault<Student>();

studentToUpdate.StudentName = "Edited student1";

//Perform delete operation

context.Students.Remove(studentList.ElementAt<Student>(0));

//Execute Inser, Update & Delete queries in the database

context.SaveChanges();

}

 

The following code does not work when adding or deleting in the List. Only regeneration is effective

using (var context = new SchoolDBEntities())

{

var studentList = context.Students.ToList<Student>();

//Add student in list

studentList.Add(new Student() { StudentName = "New Student" });

//Perform update operationStudent studentToUpdate = studentList.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();

studentToUpdate.StudentName = "Edited student1";

//Delete student from listif (studentList.Count > 0)

studentList.Remove(studentList.ElementAt<Student>(0));

//SaveChanges will only do update operation not add and delete

context.SaveChanges();

}

 

Offline entity

Offline entity management must be attached to the Context first

 

 

//disconnected entity graphStudent disconnectedStudent = newStudent() { StudentName = "New Student" };

disconnectedStudent.StudentAddress = newStudentAddress() { Address1 = "Address", City = "City1" };

using (var ctx = newSchoolDBEntities())

{

//attach disconnected Student entity graph to new context instance - ctx

ctx.Students.Attach(disconnectedStudent);

// get DbEntityEntry instance to check the EntityState of specified entity

var studentEntry = ctx.Entry(disconnectedStudent);

var addressEntry = ctx.Entry(disconnectedStudent.StudentAddress);

Console.WriteLine("Student EntityState: {0}",studentEntry.State);

Console.WriteLine("StudentAddress EntityState: {0}",addressEntry.State);

}

 

When adding multiple relationship entities, like adding a single entity, the status of each entity needs to be tracked when updating the relationship entity.

 

XIII Entity Framework concurrent processing

Add RowVersion with the type of TimeStamp field, and X modify the concurrency attribute in EDM to Fixed. EF will first check the RowVersion when updating the entity. If it is found that the RowVersion is inconsistent, it will throw a DbUpdateConcurrencyException

 

 

XIV. Greedy loading, inert loading and directional loading

Greedy loading: use Include() to automatically load associated entities

using (var context = new SchoolDBEntities())

{

var res = (from s in context.Students.Include("Standard")

where s.StudentName == "Student1"

select s).FirstOrDefault<Student>();

}

 

Execute Sql

SELECTTOP (1)

[Extent1].[StudentID] AS [StudentID],

[Extent1].[StudentName] AS [StudentName],

[Extent2].[StandardId] AS [StandardId],

[Extent2].[StandardName] AS [StandardName],

[Extent2].[Description] AS [Description]

FROM [dbo].[Student] AS [Extent1]

LEFTOUTERJOIN [dbo].[Standard] AS [Extent2] ON [Extent1].[StandardId] = [Extent2].[StandardId]

WHERE'Student1' = [Extent1].[StudentName]

 

Lazy loading: delay loading the entity associated with the object, and then load it. EF defaults to LazyLoading

using (var ctx = newSchoolDBEntities())
{

//Loading students onlyIList<Student> studList = ctx.Students.ToList<Student>(); 

Student std = studList[0]; 

//Loads Student address for particular Student only (seperate SQL query)

StudentAddress add = std.StudentAddress;

}

Directional loading: Reference() and Collection()   method

     

using (var context = new SchoolDBEntities())

            {

                //Loading students only

                IList<Student> studList = context.Students.ToList<Student>();

 

                Student std = studList.Where(s => s.StudentID == 1).FirstOrDefault<Student>();

 

                //Loads Standard for particular Student only (seperate SQL query)

                context.Entry(std).Reference(s => s.Standard).Load();

 

                //Loads Courses for particular Student only (seperate SQL query)

                context.Entry(std).Collection(s => s.Courses).Load();

            }

15: Execute SQL

Return entity

using (var ctx = newSchoolDBEntities())
{
     //The column name must match the Entity attribute
     var studentList = ctx.Students.SqlQuery("Select * from Student").ToList<Student>();
}

 

Returns a non entity type

 

using (var ctx = newSchoolDBEntities())
{
  //Get student name of string typestring studentName = ctx.Database.SqlQuery<string>("Select studentname
   from Student where studentid=1").FirstOrDefault<string>();
}

 

Execute SQL command

using (var ctx = new SchoolDBEntities())
{

    //Update commandint noOfRowUpdated = ctx.Database.ExecuteSqlCommand("Update student set studentname ='changed student by command' where studentid=1");

    //Insert commandint noOfRowInserted = ctx.Database.ExecuteSqlCommand("insert into student(studentname) values('New Student')");

    //Delete commandint noOfRowDeleted = ctx.Database.ExecuteSqlCommand("delete from student where studentid=1");
 
}

Reproduced at: https://www.cnblogs.com/wugu-ren/p/6855414.html




 

Posted by Rollo Tamasi on Thu, 28 Oct 2021 19:00:08 -0700