The Entity framework maps the entities and relationships defined in the conceptual model to the data source, using the Entity Framework to materialize the data returned by the data source as objects, to track changes made by objects, to handle concurrent processing, to propagate object changes to the data source, and so on. Today we'll discuss how to use the Entity Framework for querying, inserting, updating, and deleting data. Query
We will use the AdventureWorks database for all of today's demos, so prepare the appropriate database before you start. Querying in the EF should be fairly straightforward, simply by defining a class to inherit from "DbContext" and then defining the corresponding "Dbset" collection property. For example, the following "Adventureworkscontext" class:
Using System.Data.Entity;
Using System.Data.Entity.Infrastructure;
Using EFPowerTools.Models.Mapping;
Namespace Efpowertools.models
{public
partial class Adventureworkscontext:dbcontext
{
static Adventureworkscontext ()
{
database.setinitializer<adventureworkscontext> (null);
}
Public Adventureworkscontext ()
: Base (' Name=adventureworkscontext ')
{
} public
dbset< Employee> Employees {get; set;}
Public dbset<person> people {get; set;}}}
The life cycle of a database context begins with the creation of the object, and ends with the release of the object (or GC collection), so it is recommended that you use the "using" encoding during development so that you can eliminate the manual release of the object. As in the following code:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models;
Namespace Efpowertools
{
class program
{
static void Main (string[] args)
{
using (var db = New Adventureworkscontext ())
{
var persons = db. People.where (p => p.lastname = = "Stevens"). (p=>p.firstname);
foreach (var p in persons)
{
Console.WriteLine ("Firstname:{0},lastname:{1}", P.firstname, P.lastname);
}
}
}
}
}
In addition, the management of database connections is transparent in the EF, and we generally do not need to handle them manually, when querying an object opens the connection and closes the connection automatically after processing the result set of the query.
There are three common ways of querying data in the EF Code First mode (there are other ways to use entity SQL in model first and database first, but this is not our focus today): LINQ to entity expression queries, A method based query, native SQL query. LINQ to Entity expression Query
A query expression is a new feature of c#3.0 that consists of a set of SQL-like or XQuery declarative statements, which are not directly readable by the CLR but are converted to corresponding method calls at compile time. As in the following example:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models;
Namespace Efpowertools
{
class program
{
static void Main (string[] args)
{
using (var db = New Adventureworkscontext ())
{
var persons = from p in db. People
where p.lastname = = "Stevens" by
p.firstname
select P
; foreach (var p in persons)
{
Console.WriteLine ("Firstname:{0},lastname:{1}", P.firstname, P.lastname);
}
}
}
}
}
Method-based queries
A method based query is in fact an extension of a set of objects, and unlike a LINQ query, these methods can be identified and run directly by the CLR.
For example, the above method can be converted to the following code, their effect is the same, return is the "IQueryable" object:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models;
Namespace Efpowertools
{
class program
{
static void Main (string[] args)
{
using (var db = New Adventureworkscontext ())
{
var persons = db. People.where (p => p.lastname = = "Stevens"). (P => p.firstname);
foreach (var p in persons)
{
Console.WriteLine ("Firstname:{0},lastname:{1}", P.firstname, P.lastname);
}
}
}
}
}
Native SQL query
EF also supports native SQL queries (note the difference from Entity SQL), such as:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models;
Using System.Data.Objects;
Namespace Efpowertools
{
class program
{
static void Main (string[] args)
{
using (Var db = new Adventureworkscontext ())
{
var persons = db. People.sqlquery ("select * from Person.person WHERE lastname= ' Stevens '");
foreach (var p in persons)
{
Console.WriteLine ("Firstname:{0},lastname:{1}", P.firstname, P.lastname);
}
}
}
}
}
Not only that, the EF also supports non entity type queries:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models;
Using System.Data.Objects;
Namespace Efpowertools
{
class program
{
static void Main (string[] args)
{
using (Var db = new Adventureworkscontext ())
{
var persons = db. Database.sqlquery<string> ("Select FirstName from Person.person WHERE lastname= ' Stevens '"). ToList ();
foreach (var p in persons)
{
Console.WriteLine ("Firstname:{0}", p);
}
}
}}
SQL commands with no return value are supported, of course:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models;
Using System.Data.Objects;
Namespace Efpowertools
{
class program
{
static void Main (string[] args)
{
using (Var db = new Adventureworkscontext ())
{
db. Database.executesqlcommand ("UPDATE person.person SET namestyle=1 WHERE businessentityid= ' 1813 '");}}
}
Increase
There are generally two ways to add operations to the EF: First, create the object directly, then invoke the "Add ()" Method of "Dbset" to add it, and the second is to invoke the "Entry ()" Method of the database context and set the corresponding state. Whichever way you use it, you end up calling "SaveChange ()" for submission. Such as:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models; Namespace Efpowertools {class Program {static void Main (string[] args) {using (var
db = new Adventureworkscontext ()) {The var Stephen = new Person {
businessentityid=20778, persontype= "EM", Namestyle=false, Title= "Architec", firstname= "Stephen", lastname= "Chow", Em
Ailpromotion=1, rowguid = Guid.NewGuid (), ModifiedDate = DateTime.Now
}; Db.
People.add (Stephen); var jeffrey = new Person {BusinessEntityID = 20779, PersonType = "EM", Namestyle = false, Title = "Engineer", FirstName = "Jeffrey" , LastName = "Lee", emailpromotion = 0, Rowguid=guid.newguid ()
, Modifieddate=datetime.now}; Db. Entry (Jeffrey).
state = entitystate.added; Db.
SaveChanges ();
}
}
}
}
Effect as shown:
In addition, the navigation properties that assign an object to another object when it contains navigation properties can also achieve the added effect (the Add effect can also be achieved by invoking the "Add ()" Method of the navigation property when the navigation property is a "Dbset" collection, for example, in "Person.person" We have added two records above, but for the "person" class, the navigation properties "EmailAddress" and "Password" are not added to the corresponding "EmailAddress" and "Password" tables. At this point we can add in the following ways:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models; Namespace Efpowertools {class Program {static void Main (string[] args) {using (var
db = new Adventureworkscontext ()) {var password = new Password {
businessentityid=20778, PasswordHash = "zegqh9qzipilgybhyw/dd1fjqnpdqyiaa+bffkx5/jg=", PasswordSalt = "7iy/umc=", Rowguid=guid.newguid (), modifieddate=date
Time.now}; var email = new EmailAddress {BusinessEntityID = 20778, emailaddr Ess1 = "StephenChow@outlook.com", rowguid = Guid.NewGuid (), ModifiedDate = Datetim E.now}; var person = db.
People.find (20778); Person.
Password = Password; Person.
Emailaddresses.add (email); Db.
SaveChanges ();
}
}
}
}
The view will see that a record is added to the "EmailAddress" table (as is the "Password" table):
Status Tracking
One thing we need to emphasize here is state tracking, and for the above operation, if we call the "Attach ()" method to track the entity or set the state of the entity, then the data will not be saved to the database:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models; Namespace Efpowertools {class Program {static void Main (string[] args) {using (var
db = new Adventureworkscontext ()) {The var Stephen = new Person {
BusinessEntityID = 20778, PersonType = "EM", Namestyle = False,
Title = "Architec", FirstName = "Stephen", LastName = "Chow",
EmailPromotion = 1, rowguid = Guid.NewGuid (), ModifiedDate = DateTime.Now
}; Db.
People.add (Stephen); Db.
People.attach (Stephen); Db. Entry (Stephen). state = entitystate.unchanged;//with Upper db. People.attach (Stephen), acting as db.
SaveChanges ();
}
}
}
}
Entity tracking with the Attach () method sets the state of the entity to "unchanged" when the entity is in an unmodified state, and the EF does not perform a modification when the SaveChange () method is executed. Conversely, if you set the entity status to "Modified" at this point, the EF performs the update operation. So since the EF data modification operation (add, update, delete) is based on the entity state, then why our increase before the operation is normal without the need to manually modify its state. The reason is that the EF automatically discovers state changes, and the state discovery is automatic when the following method is invoked:
· Dbset.find · Dbset.local · Dbset.remove · Dbset.add · Dbset.attach · Dbcontext.savechanges · Dbcontext.getvalidationerrors · Dbcontext.entry · Dbchangetracker.entries |
Of course, not all the time we need EF to automatically discover state changes, setting the "DbContext.Configuration.AutoDetectChangesEnabled" property to "false" to disable automatic discovery.
|
Note: When EF operates on data, it sometimes throws: Validation failed for one or more entities. The ' entityvalidationerrors ' property is for more details. You can use try{} catch (Dbentityvalidationexception ex) {} to capture the exception, place the mouse over an ex, and then step through the information of ex to resolve it. |
Remove
Here's a look at the EF delete operation:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using Efpowertools.models;
Using System.Data.Objects;
Namespace Efpowertools
{
class program
{
static void Main (string[] args)
{
using (Var db = new Adventureworkscontext ())
{
var mail = db. Emailaddresses.where (m => m.emailaddressid = 19977). FirstOrDefault ();
Db. Emailaddresses.remove (mail);
Db. SaveChanges ();}}}
Of course, with the above status tracking discussion I believe you can also think of the following deletion method:
Using System;
Using System.Collections.Generic;
Using System.Data;
Using System.Data.Entity.Validation;
Using System.Linq;
Using System.Text;