The Entity Framework enables you to query, insert, update, and delete data, expressed as typed common language runtime (CLR) objects that are instances of entity types. The entity types represent the entities defined in the conceptual model. The Entity Framework maps entities and relationships that are defined in a conceptual model to a data source. The Entity Framework provides facilities to do the following: materialize data returned from the data source as objects; track changes that were made to the objects; handle concurrency; propagate object changes back to the data source; and bind objects to controls. You can use LINQ to Entities, Entity SQL Language, or Query Builder Methods (Entity Framework) to execute queries against the conceptual model.
Customizable Code-Generation: EF4 leverages the T4 code generation templating engine in Visual Studio. You can now write your own templates that specify exactly how you want code generation to happen; or you can modify the built-in templates such as the Entity Object Code Generator or Self Tracking Entities Code Generator templates: http://blogs.msdn.com/adonet/archive/2009/05/19/sneak-peek-using-code-generation-templates-with-the-entity-framework-4-0.aspx
Self-Tracking Entities & N-Tier support: Visual Studio 2010 includes code-generation templates for Self Tracking Entities that allow you to easily build N-Tier applications. There are also new APIs in the product that offer you more control in N-Tier scenarios. : http://msdn.microsoft.com/en-us/library/ee789839(v=VS.100).aspx
Model Defined Functions LINQ support: Model Defined Functions allow you to define composable functions in your model using Entity SQL. http://blogs.msdn.com/adonet/archive/2009/05/14/sneak-preview-model-defined-functions.aspx
EntityDataSource support for QueryExtender, POCO and FKs: EntityDataSource control now includes support for ASP.NET QueryExtender and POCO entities. QueryExtender is a new addition to ASP.NET, which allows you to have more control over the data retrieval query of a Data Source while leveraging LINQ capabilities of EF.
The Entity Data Model Tools can generate a class derived from ObjectContext that represents the entity container in the conceptual model. This object context provides the facilities for tracking changes and managing identities, concurrency, and relationships. This class also exposes a SaveChanges method that writes inserts, updates, and deletes to the data source. Like queries, these changes are either made by commands automatically generated by the system or by stored procedures that are specified by the developer.
The EntityClient provider extends the ADO.NET provider model by accessing data in terms of conceptual entities and relationships. It executes queries that use Entity SQL. Entity SQL provides the underlying query language that enables EntityClient to communicate with the database
——————————————————————————————————————————-
•Address
•Contact
•Product
•SalesOrderDetail
•SalesOrderHeader
——————————————————————————————————————————-
QueryExtender and Model-Defined Functions
ADO.NET EntityObject Generator
——————————————————————————————————————————-
http://blogs.msdn.com/efdesign/archive/2009/01/22/customizing-entity-classes-with-t4.aspx
ADO.NET Entity Designer generates classes from the CSDL portion of the EDMX file using the EntityClassGenerator APIs.
how to customize the code generation for a variety of scenarios:
Make the generated ObjectContext internal
Make the generated ObjectContext and Entity classes implement a user-defined interface
Add user-defined CLR attributes to generated ObjectContext and generated Entity classes
Influence generated classes based on structural annotations in CSDL
Generate the ObjectContext and Entity classes into separate files
Generate “proxy classes” for the generated classes
Partially or fully change how classes are generated, maybe even generate additional (non code) artifacts in the project
Completely replace entity framework code generation with custom code
Generate POCO classes from the model to use as a starting point in my applications
Generate self-tracking entity classes
——————————————————————————————————————————-
http://blogs.msdn.com/adonet/archive/2008/01/24/customizing-code-generation-in-the-ado-net-entity-designer.aspx
SSDL – store schema definition language
Mapping specification language (MSL)
TT – Text Templates 4 TT4
http://msdn.microsoft.com/en-us/library/bb126445.aspx
Conceptual schema definition language (CSDL) is an XML-based language that describes the entities, relationships, and functions that make up a conceptual model of a data-driven application. This conceptual model can be used by the Entity Framework or ADO.NET Data Services. The metadata that is described with CSDL is used by the Entity Framework to map entities and relationships that are defined in a conceptual model to a data source. For more information, see SSDL Specification and MSL Specification.
——————————————————————————————————————————-
CSDL is the Entity Framework’s implementation of the Entity Data Model.
In an Entity Framework application, conceptual model metadata is loaded from a .csdl file (written in CSDL) into an instance of the System.Data.Metadata.Edm.EdmItemCollection and is accessible by using methods in the System.Data.Metadata.Edm.MetadataWorkspace class. The Entity Framework uses conceptual model metadata to translate queries against the conceptual model to data source-specific commands.
——————————————————————————————————————————-
Entity Data Model Designer (Entity Designer):: http://msdn.microsoft.com/en-us/library/cc716685.aspx
.edmx File Overview.:: http://msdn.microsoft.com/en-us/library/cc982042.aspx
Entity Data Model.: http://msdn.microsoft.com/en-us/library/ee382825.aspx
——————————————————————————————————————————-
The conceptual model metadata can be used to generate the object-layer code for an Entity Framework application. For more information, see Generated Code Overview (Entity Data Model Designer) http://msdn.microsoft.com/en-us/library/cc982041.aspx and How to: Use EdmGen.exe to Generate Object-Layer Code. http://msdn.microsoft.com/en-us/library/cc716790.aspx
——————————————————————————————————————————-
Entity Framework Overview:: http://msdn.microsoft.com/en-us/library/bb399567.aspx
ADO.NET Entity Data Model Tools:: http://msdn.microsoft.com/en-us/library/bb399249.aspx
——————————————————————————————————————————-
ObjectContext.ObjectMaterialized Event
This event is raised after all scalar, complex, and reference properties have been set on an object, but before collections are loaded. If an object with the same key value exists in the object context, the Entity Framework will not recreate the object and this event will not be raised.
——————————————————————————————————————————-
ObjectContext Class
Provides facilities for querying and working with entity data as objects.
The ObjectContext class is the primary class for interacting with data as objects that are instances of entity types that are defined in a conceptual model. An instance of the ObjectContext class encapsulates the following:
•A connection to the database, in the form of an EntityConnection object.
•Metadata that describes the model, in the form of a MetadataWorkspace object.
•An ObjectStateManager object that manages objects persisted in the cache. tracks objects during create, update, and delete operations
When the object layer that represents a conceptual model is generated by the Entity Data Model tools, the class that represents the EntityContainer for the model is derived from the ObjectContext.
EntityObject
By default, the ADO.NET Entity Data Model tools generate EntityObject derived entity types. When you work with EntityObject derived types, the object context manages the relationships between your objects, tracks changes as they occur, and supports lazy loading in the most efficient manner. However, the EntityObject derived types have strong dependency on the Entity Framework. If you are working with architectures that require persistence ignorance (for example, test- driven development or domain-driven development) or you have existing domain classes, consider using POCO or POCO proxies.
Self-Tracking Entities
The EntityObjectderived types, POCO, and POCO proxy types work well in applications where entity objects can be attached to the object context that handles change tracking. However, when you have to transfer full graphs of entities to a tier where the object context is not available, you must decide how to track changes and report those changes back to the object context. Starting with the .NET Framework version 4, self-tracking entities can record changes to scalar, complex, and navigation properties. Self-tracking entities do not depend on the Entity Framework. The ADO.NET Self-Tracking Entity Generator template generates self-tracking entities
——————————————————————————————————————————-
——————————————————————————————————————————-
// Create the ObjectContext.
ObjectContext context =
new ObjectContext("name=AdventureWorksEntities");
// Set the DefaultContainerName for the ObjectContext.
// When DefaultContainerName is set, the Entity Framework only
// searches for the type in the specified container.
// Note that if a type is defined only once in the metadata workspace
// you do not have to set the DefaultContainerName.
context.DefaultContainerName = "AdventureWorksEntities";
ObjectSet<Product> query = context.CreateObjectSet<Product>();
// Iterate through the collection of Products.
foreach (Product result in query)
Console.WriteLine("Product Name: {0}", result.Name);
-------------------------------------------------------------------------------------------------------------------------------
——————————————————————————————————————————-
http://blogs.msdn.com/adonet/archive/2008/01/24/sampleedmxcodegenerator-sources.aspx
How to add custom attributes to my generated classes
——————————————————————————————————————————-
“Database Script Generation” properties:
Database Generation Workflow – Controls the overall process by which the conceptual model is translated into a database script. The default workflow is “TablePerTypeStrategy.xaml”.
DDL Generation Template – Is called by the default database generation workflow to transform the generated database model to DDL. More on this below.
First, let’s take a look at TablePerTypeStrategy.xaml – it is located in Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen. If we open this file in Visual Studio, we see that it is a Workflow Foundation (WF) workflow
The first activity, “CsdlToSsdlAndMslActivity” generates the store model (SSDL) for the EDM, and then generates the mappings (MSL) that connect the two. It has the following properties
The “MslOutputGeneratorType” specifies a class that generates MSL based on a table-per-type mapping strategy. The “OuputGeneratorType” generates SSDL. Rather than replacing this activity and all of the plumbing it provides, you can replace these two classes with your own if you want to change the mapping strategy or otherwise alter the system.
http://blogs.msdn.com/adonet/archive/2009/11/05/model-first-with-the-entity-framework-4.aspx
——————————————————————————————————————————-
Query builder methods
These methods of ObjectQuery enable you to construct queries that are the same as Entity SQL without having to construct a query string. Because these methods always return an ObjectQuery, you can build queries by calling methods in series or use them to extend an Entity SQL query. Some methods, such as Where and OrderBy, take Entity SQL fragments as parameters. Query builder methods can be followed by certain LINQ standard query operators
The ObjectQuery generic class represents a query that can return a collection of zero or more typed objects. An ObjectQuery belongs to an ObjectContext that contains the connection and metadata information that is necessary to compose and execute the query. You can construct an ObjectQuery with a new operator and pass a query string and the object context to the constructor. However, a more common scenario is to use properties on an ObjectContext derived class to get an ObjectQuery instance that represents a collection of entity sets. Typically, the ObjectContext is subclassed, either by a class generated by the Entity Framework tools or by your POCO classes, and the properties on the object context return entity sets as either an ObjectQuery (in .NET Framework version 3.5 SP1) or as an ObjectSet (in .NET Framework version 4). The ObjectSet class extends the ObjectQuery class to provide functionality, such as adding and deleting objects, in the context of a typed entity set.
This is the query builder method example.
string firstName = @"Frances";
string lastName = @"Adams";
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
// Get the contacts with the specified name.
ObjectQuery<Contact> contactQuery = context.Contacts
.Where("it.LastName = @ln AND it.FirstName = @fn",
new ObjectParameter("ln", lastName),
new ObjectParameter("fn", firstName));
// Iterate through the collection of Contact items.
foreach (Contact result in contactQuery)
Console.WriteLine("Last Name: {0}; First Name: {1}",
result.LastName, result.FirstName);
}
An object query is executed when:
•It is enumerated by a foreach (C#) or For Each (Visual Basic) statement.
•It is enumerated by a collection operation such as ToArray, ToDictionary or ToList.
•The Execute method is explicitly called.
•LINQ operators such, as First or Any are specified in the outermost part of the query. For more information, see Query Builder Methods (Entity Framework).
Note, if as a result of a query execution, nothing was returned from the data source, the results will contain an empty collection and not a null.
——————————————————————————————————————————-
Entity Framework Features Not Supported by the Entity Designer
The following are Entity Framework features that are not currently supported by the Entity Designer.
•Multiple entity sets per type.
•Creating entity sets for non-root types.
•Table-per-concrete class mapping.
•Using EntityType properties in mapping conditions.
•Unmapped abstract types. When you create an abstract entity type with the Entity Designer, the type must be mapped to a table or view.
•Creating conditions on association mappings.
•Mapping associations directly to stored procedures. Mapping many-to-many associations is not supported. You can indirectly map other associations to stored procedures along with entity types by mapping the appropriate navigation properties to stored procedure parameters.
•Creating conditions on Function Import mappings.
•Annotations.
•Query views.
•Models that contain references to other models.
•Creating associations without corresponding navigation properties.
•Adding or editing storage model objects. (Deleting storage model objects is supported.)
•Adding, editing, or deleting functions that are defined in the conceptual model.
————————————————————————————————————————
Building N-Tier Applications (Entity Framework)
Entity types generated by the Entity Data Model generator tool (EdmGen.exe) and the Entity Data Model Wizard have SerializableAttribute and DataContractAttribute applied. This enables objects to be serialized by using binary serialization, XML serialization, and Windows Communication Foundation (WCF) data contract serialization.
Extending Partial Classes :: How to: Customize Generated Data Objects (Entity Framework).
When data classes are generated by the Entity Data Model tools, they are implemented in partial classes. You can add functionality to objects by extending the generated partial data classes. Having partial classes enables you to extend these classes with custom methods and properties in a separate source file without having to worry about losing your customization when the generated files are refreshed.
——————————————————————————————————————————-
Managing Connections and Transactions
By default, the Entity Framework manages the connection to the database. However, you can manually manage both connections and transactions in your Entity Framework application.
By default, the Entity Framework implements an optimistic concurrency model. This means that locks are not held on data in the data source between when the data is queried and the data is updated. The Entity Framework saves object changes to the database without checking for concurrency. For entities that might experience a high degree of concurrency, we recommend that the entity define a property in the conceptual layer with an attribute of ConcurrencyMode=”fixed”
When this attribute is used, the Entity Framework checks for changes in the database before saving changes to the database. Any conflicting changes will cause an OptimisticConcurrencyException.
An OptimisticConcurrencyException can also occur when you define an Entity Data Model that uses stored procedures to make updates to the data source. In this case, the exception is raised when the stored procedure that is used to perform updates reports that zero rows were updated.
You may choose to use transactions as an alternative to optimistic concurrency.
The Entity Framework opens connections only when required, for example to execute a query or to call SaveChanges, and then closes the connection when the operation is complete.
Calling any of the following methods opens the connection:
•SaveChanges or Refresh on ObjectContext.
•FirstOrDefault, or First on ObjectQuery.
•Load on EntityCollection.
•Load on EntityReference.
•Any Language-Integrated Query (LINQ) method or ObjectQuery query builder method, such as Where, OrderBy, or Select.
When a query method is called, the connection is opened, and it remains open until the ObjectResult has been completely consumed or disposed.
The Entity Framework supports automatic transaction enlistment. This means that activities performed within an object context, such as executing queries and saving changes to data in the data source, can be isolated in the data source by executing the operation within a System.Transactions transaction. Transactions are used in the Entity Framework to do the following actions:
•To execute multiple operations against the data source that must be highly consistent, such as queries that depend on the successful completion of object changes.
•To coordinate changes in the object context with other distributed operations, such as sending an e-mail notification or writing to a message queue.
Transactions that require the enlistment of additional resource managers are called distributed transactions. Distributed transactions use a distributed transaction coordinator (DTC) to manage the resources that are required to complete the transaction. Promotion of a transaction to a DTC can be a relatively expensive process to establish and complete. Some resource managers, like SQL Server 2005, support the Promotable Single Phase Enlistment (PSPE) transaction protocol. This allows a resource manager to host a transaction that can later be escalated to be managed by the distributed transaction coordinator (DTC) if necessary.
——————————————————————————————————————————-
•When you call SaveChanges, if a current transaction exists, the Entity Framework uses this transaction for operations against the data source. Otherwise, it creates a new transaction for the operation. You can define transactions by using EntityTransaction, Transaction, or TransactionScope.
•Promotion of a transaction to a DTC may occur when a connection is closed and reopened within a single transaction. Because the Entity Framework opens and closes the connection automatically, you should consider manually opening and closing the connection to avoid transaction promotion.
To enlist in an existing transaction, the Entity Framework might close and reopen the connection.
——————————————————————————————————————————-
This example defines a TransactionScope. The TransactionScope ensures that changes to objects in the object context are coordinated with a message queue. The Entity Framework uses this transaction when it saves changes to the database. When an UpdateException occurs, the operation is retried up to two times. When the operation succeeds, the changes in the object context are accepted. For more information, see Managing Connections and Transactions (Entity Framework).
This example uses a long-running object context, which is disposed after the transaction succeeds or after all retries have been attempted.
——————————————————————————————————————————-
http://msdn.microsoft.com/en-us/library/bb896325.aspx
The following considerations apply when you use transactions with the Entity Framework:
•Only operations against the data source are transacted. Changes made to objects in the object context are not transacted. Changes to objects in the context are visible outside the transaction scope.
•When the Entity Framework creates a new transaction for a SaveChanges operation, changes to objects in the object context are not accepted until the transaction completes. This ensures that the state of the object context and the data source are consistent.
•When you plan to retry operations in a transaction, you must ensure that the status of objects in the context is not reset before the transaction is completed. To do this, you must call SaveChanges with a value of false for the acceptChangesDuringSave parameter, and then call AcceptAllChanges only after other operations in the transaction have completed successfully.
——————————————————————————————————————————-
Managing Transactions
In the Entity Framework, there are two ways to use transactions: automatic and explicit. Automatic transactions use the System.Transactions namespace, and explicit transactions use the EntityTransaction class.
Filed under:
ASP.NET,
Code,
Database,
Reference Tagged:
.NET,
ADO.NET,
ASP,
C#,
Code,
data Access,
Data Services,
EF4,
Entity,
Feeds,
Frameworks,
OData,
RIA,
RSS,
SQL,
SQL Server,
WCF