Databases Reference
In-Depth Information
To insert a new row into a database table, you need to create a new entity instance and
add it to the context as shown next. For newly added entities, the object context automat-
ically generates INSERT SQL statements.
using (NorthwindEntities context = new NorthwindEntities())
{
Product p = new Product() { ProductName = “Mukuzani” };
context.Products.AddObject(p);
context.SaveChanges();
}
LINQ to Entities
Language Integrated Query functionality is not unique to the Entity Framework. It is a
general purpose feature of the C# and Visual Basic programming languages that takes
advantage of the .NET classes in the System.Linq namespace that define the various query
expressions and operations. Entity Framework implements a LINQ flavor, called LINQ to
Entities, that allows translating .NET queries into the underlying SQL queries for Microsoft
SQL Server and other database engines.
Query Execution
LINQ queries are objects that implement an IQueryable<T> interface and store the query
compiled in a form of a LINQ expression:
IQueryable<Product> query = from p in context.Products
where p.Supplier.City == “London”
select p;
Console.WriteLine(query.Expression);
The query is not executed until it is actually accessed by enumeration, as in this example:
foreach (Product p in query)
Console.WriteLine(p.ProductName);
or with one of the LINQ extension methods, such as First .
Product product = query.First();
The query object itself does not store the entities retrieved from the database. This is
important mainly for performance reasons—every time you access the query by enumerat-
ing entities it returns or call one of the LINQ extension methods, a new SQL query is sent
to the database engine. If you need to access the query results multiple times, it would be
much faster to store the entities the query returns in a list and access the list, which does
not trigger the query execution:
 
 
Search WWH ::




Custom Search