Your best source of information and news about seven, xp and vista on the internet

ARTICLES TOP 50 Spyware Virus Vista SOFT Vista HELP

ADO.NET

You are currently browsing the articles from MS Windows Vista Compatible Software matching the category ADO.NET.

DevForce, Enterprise Applications, and the ADO.NET Entity Framework

DevForceAndTheEntityFramework

DevForce Data Services fills a gap in the application infrastructure stack between where your Data Access Layer (DAL) ends and your client application begins. The gap concerns your “business logic layer”. The gap concerns your “business logic layer”. How your raw data become business objects with behavior, logic, and rules. How your raw data become business objects with behavior, logic, and rules. How your business objects traverse tiers and cross the network … securely and reliably. How your business objects traverse tiers and cross the network … securely and reliably. How you query for them with LINQ and save changes transactionally. How you query for them with LINQ and save changes transactionally. How you do all of this at scale and with maximum performance. How you do all of this at scale and with maximum performance. DevForce Data Services fills this gap so you don’t have to reinvent it, cobble it, maintain it, and defend it. DevForce Data Services fills this gap so you don’t have to reinvent it, cobble it, maintain it, and defend it. We’ve got eight years of tough customer experience, with production applications in the field spanning the spectrum of .NET client technologies: WinForms, ASP.NET, WPF, and now Silverlight. We’ve got eight years of tough customer experience, with production applications in the field spanning the spectrum of. NET client technologies: WinForms, ASP.NET, WPF, and now Silverlight.

Features

Why DevForce? Why DevForce?
Data Access

N-tier data access is hard. N-tier data access is hard. Constructing a remote domain model for your data is hard. Constructing a remote domain model for your data is hard. DevForce simplifies n-tier persistence and provides a rich domain model on which to build your application. DevForce simplifies n-tier persistence and provides a rich domain model on which to build your application. Stop writing plumbing and infrastructure code and focus on your business logic and user experience. Stop writing plumbing and infrastructure code and focus on your business logic and user experience.

Single Domain Model

You should not have to duplicate your business logic in multiple places. You should not have to duplicate your business logic in multiple places. The mobile business objects in DevForce enable you to use a single domain model whether you are writing client-side or server-side. The mobile business objects in DevForce enable you to use a single domain model whether you are writing client-side or server-side. The same domain model works with all of our DevForce products, so you can have multiple faces for your application in different technologies such as WPF, WinForms, ASP.NET, or Silverlight. The same domain model works with all of our DevForce products, so you can have multiple faces for your application in different technologies such as WPF, WinForms, ASP.NET, or Silverlight.

Rich Domain Model

DevForce provides you with rich business objects with real behavior. DevForce provides you with rich business objects with real behavior. Use a domain model that represents your problem, not just flat data transfer objects, where you have to do all the bookkeeping and re-implement your logic. Use a domain model that represents your problem, not just flat data transfer objects, where you have to do all the bookkeeping and re-implement your logic.

Verification Engine

Verify the correctness of your business objects and provide helpful error messages to the user. Verify the correctness of your business objects and provide helpful error messages to the user. Supports cross-field, cross-object, and dynamic validation, and seamlessly integrates with Silverlight validation. Supports cross-field, cross-object, and dynamic validation, and seamlessly integrates with Silverlight validation. This keeps your business logic in your business objects and out of the UI. This keeps your business logic in your business objects and out of the UI.

Entity Framework Integration

Standardize on Microsoft’s next generation ORM framework. Standardize on Microsoft’s next generation ORM framework. DevForce is built upon the Entity Framework, enables it to work in n-tier, makes it easier to use, and adds all the features you see here plus more. DevForce is built upon the Entity Framework, enables it to work in n-tier, makes it easier to use, and adds all the features you see here plus more.

Security

DevForce is integrated with the ASP.NET Membership, Roles, and Profiles services so you can reuse your existing security infrastructure. DevForce is integrated with the ASP.NET Membership, Roles, and Profiles services so you can reuse your existing security infrastructure. If you require a custom authentication strategy, DevForce provides an interface so you can implement your own custom logic. If you require a custom authentication strategy, DevForce provides an interface so you can implement your own custom logic. Also, no connection string is exposed on the client and server-side security checks prevent unauthorized access even if the client is compromised. Also, no connection string is exposed on the client and server-side security checks prevent unauthorized access even if the client is compromised.

Caching & Performance

DevForce applications are snappy because the domain model executes inside the Silverlight client. DevForce applications are snappy because the domain model executes inside the Silverlight client. Client-side caching greatly reduces the number of trips to the server and simplifies asynchronous programming. Client-side caching greatly reduces the number of trips to the server and simplifies asynchronous programming. Data compression further reduces network latency and improves performance. Data compression further reduces network latency and improves performance.

Full n-tier LINQ Support

Get the full power of LINQ in an n-tier application. Get the full power of LINQ in an n-tier application. LINQ-to-Entities only operates 2-tier, and other LINQ implementations only support a narrow range of queries. LINQ-to-Entities only operates two-tier, and other LINQ implementations only support a narrow range of queries. DevForce supports them all including subqueries, projections, and aggregation. DevForce supports them all including subqueries, projections, and aggregation.

MVVM and Best Practices

DevForce is built around good architectural practices such as MVC and MVVM and enables you to conveniently keep your UI and business logic where they belong without sacrificing usability or functionality. DevForce is built around good architectural practices such as MVC and MVVM and enables you to conveniently keep your UI and business logic where they belong without sacrificing usability or functionality.

Offline Execution

Use your application while disconnected or partially connected to the internet. Use your application while disconnected or partially connected to the internet. Save your work in isolated storage and resume working later. Save your work in isolated storage and resume working later.

Multiple Data Sources

Use multiple back-end databases in a single domain model. Use multiple back-end databases in a single domain model. Navigate cross-database relations using object properties. Navigate cross-database relations using object properties. Save all your changes safely in a distributed transaction. Save all your changes safely in a distributed transaction.

Scalability

Client-side caching, connection pooling, and a stateless and multi-core enabled server provide DevForce applications with excellent scalability and fault-tolerant characteristics. Client-side caching, connection pooling, and a stateless and multi-core enabled server provide DevForce applications with excellent scalability and fault-tolerant characteristics.

Lifecycle Events

In addition to writing static business logic, you can dynamically modify behavior at runtime by injecting your logic before or after a get or set, and by hooking into the object lifecycle events (fetching, fetched, saving, saved). In addition to writing static business logic, you can dynamically modify behavior at runtime by injecting your logic before or after a get or set, and by hooking into the object lifecycle events (fetching, fetched, saving, saved).


Filed under: .NET, Architecture, Database, Design, Products Tagged: .NET, ADO.NET, BLL, DAL, DB, DevForce, EF, EF4, Entity Framework, Rules

Written by Visitor Blogs on August 6th, 2010 with no comments.
Read more articles on Rules and EF4 and BLL and DevForce and Entity Framework and EF and DAL and ADO.NET and Design and .Net and Database and otherSoftware and DB and Architecture and Products.

The Exception Handling Application Block :: Microsoft Enterprise Library 5.0

The Enterprise Library Exception Handling Application Block helps developers and policy makers implement common design patterns and create a consistent strategy for processing exceptions that occur in all architectural layers of an enterprise application. It is designed to support the typical code contained in catch statements in application components. Instead of repeating this code (such as code that logs exception information) in identical catch blocks throughout an application, the Exception Handling Application Block allows developers to encapsulate this logic as reusable exception handlers. The Exception Handling Application Block includes four exception handlers:

  • Wrap handler. This exception handler wraps one exception around another.
  • Replace handler. This exception handler replaces one exception with another.
  • Logging handler. This exception handler formats exception information, such as the message and the stack trace. Then the logging handler passes this information to the Enterprise Library Logging Application Block so that it can be published.
  • Fault Contract exception handler. This exception handler is designed for use at Windows® Communication Foundation (WCF) service boundaries, and generates a new Fault Contract from the exception.

You can extend the Exception Handling Application Block by implementing custom handlers, and administrators can manage the configuration of the block to, for example, turn on additional debugging instrumentation or change the behavior of the block in line with changes to business requirements. The configuration can even be managed using Group Policy tools.

What Does the Exception Handling Application Block Do?

A comprehensive exception-handling strategy will usually:

  • Notify the user with a friendly message
  • Store details of the exception in a production log or other repository
  • Alert the customer service team to the error
  • Assist support staff in cross-referencing the exception and tracing the cause

The Exception Handling Application Block lets you associate exception types with named policies. You do this by using the configuration tools. Policies specify the exception handlers that execute when the block processes a particular exception type. Exception handlers are .NET classes that encapsulate exception handling logic and implement the Exception Handling Application Block interface named IExceptionHandler.

You can chain these handlers together so that a series of them execute when the associated exception type is handled. The following are some examples of named policies and descriptions of what they might provide:

  • Base policy. This policy logs the exception and re-throws the original exception.
  • Secure policy. This policy logs the exception, replaces the original exception with a custom exception, and throws the new exception.
  • Expressive policy. This policy wraps the original exception inside another exception and throws the new exception.

The following schematic illustrates examples of cross-layer and single-application component exception handling.

Determining Appropriate Exception Policies and Actions

Exception Propagation

There are three main ways to propagate exceptions:

  • Let the exception propagate automatically. With this approach, you do nothing and deliberately ignore the exception. This causes control to move immediately from the current code block up the call stack until a catch block with a filter that matches the exception type is found.
  • Catch and re-throw the exception. With this approach, you catch and react to the exception, and clean up or perform any other required processing within the scope of the current method. If you cannot recover from the exception, you re-throw the same exception to your caller.
  • Catch, wrap, and throw the wrapped exception. As an exception propagates up the call stack, the exception type becomes less relevant. When an exception is wrapped, a more relevant exception can be returned to the caller.

Advanced Configuration Scenarios

The Enterprise Library standalone configuration console and the Visual Studio integrated configuration editor allow you to satisfy a range of advanced configuration scenarios based on external configuration sources such as disk files. For example, you can:

  • Read configuration information from a wide range of sources.
  • Enforce common configuration settings across multiple applications.
  • Share configuration settings between applications.
  • Specify a core set of configuration settings that applications can inherit.
  • Merge configuration settings that are stored in a shared location.
  • Create different configurations for different deployment environments.

The default and simplest scenario for configuring Enterprise Library is to configure your application using the configuration tool without adding a Configuration Sources section or any configuration sources.

Example Application Code

with the Exception Handling Application Block the same application could use the following code to define the method and then execute it. It assumes you have resolved the class through the container to obtain a reference to an ExceptionManager instance and stored it in a variable named exManager.

DataSet customersDataSet = exManager.Process(() =>
                             GetDataSet("GetAllCustomers"), "Data Access Policy");

Adding Application Code

First, prepare your application to use the Logging Application Block. The following procedure describes how to include the necessary Enterprise Library assemblies and elements in your code.

To prepare your application

  1. Set a reference to the Logging Application Block assembly:
    • If you are using C#, in Visual Studio, right-click References in Solution Explorer, and then click Add References to add references to the following assemblies:
      • Microsoft.Practices.Unity.dll
      • Microsoft.Practices.Unity.Interception.dll
      • Microsoft.Practices.ServiceLocation.dll
      • Microsoft.Practices.EnterpriseLibrary.Common.dll
      • Microsoft.Practices.EnterpriseLibrary.Logging.dll
  • To use elements from the Logging Application Block without fully qualifying the element reference, you can add the following using statements (C#) or Imports statements (Visual Basic) to the top of your source code file.
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation;
using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;

The ExtraInformation providers gather context information that is useful but not always necessary because it is expensive to collect. Examples are stack trace information and COM+ information. The ExtraInformation providers add the information to a dictionary. You can choose which providers to use (if any) and add the resulting dictionary to the LogEntry.ExtendedProperties property.

Filters are optional. You only need to import the Microsoft.Practices.EnterpriseLibrary.Logging.Filters namespace if you are going to refer to specific filters in your application code.

If you are using the DatabaseTraceListener class, you must also do the following:

Configure the application to use the Data Access Application Block.

you must prepare your application to use the Data Access Application Block. After you do that, you can create the Database object and call the appropriate method overloads.

To prepare your application

  1. Add a reference to the Data Access Application Block assembly. In Visual Studio, right-click your project node in Solution Explorer, and then click Add Reference. Click the Browse tab, and then navigate to the location of the Microsoft.Practices.EnterpriseLibrary.Data.dll assembly. Select the assembly, and then click OK to add the reference.
  2. Following the same procedure, add references to the following assemblies:
    • Microsoft.Practices.EnterpriseLibrary.Common.dll
    • Microsoft.Practices.Unity.dll
    • Microsoft.Practices.ServiceLocation.dll
    • Microsoft.Practices.Unity.Interception.dll.
  • To use elements from Data Access Application Block without fully qualifying the element reference, you can add the following using statement (C#) or Imports statement (Visual Basic®) to the top of your source code file.
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;

Execute the script named CreateLoggingDb.cmd (located in the Source\Blocks\Logging\Src\DatabaseTraceListener\Scripts folder) to create the Logging database.

It is also a good idea to add a reference to the Microsoft.Practices.EnterpriseLibrary.Logging.Database.dll to your project so that the assembly required at run time is copied to the output folder.

  1. Add a reference to the Exception Handling Application Block assembly. In Visual Studio®, right-click your project node in Solution Explorer, and then click Add Reference. Click the Browse tab, select the Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll assembly, and then click OK.
  2. Following the same procedure, set a reference to the following assemblies,
    • Microsoft.Practices.EnterpriseLibrary.Common.dll
    • Microsoft.Practices.ServiceLocation.dll
    • Microsoft.Practices.Unity.dll
    • Microsoft.Practices.Unity.Interception.dll

Add the application code.

Generally, code that uses the Exception Handling Application Block must complete the following steps:

  • Obtain an instance of the ExceptionManager class. For more details, see Creating Application Block Objects.
  • Catch an exception.
  • Process an exception policy.
  • Re-throw the original exception where appropriate.

Sending an Exception to the Exception Handling Application Block

Interaction between application code and the Exception Handling Application Block occurs when the application code catches an exception and sends it to the block to be handled. Application developers do not have to know how exceptions will be handled because they have to specify only the name of the relevant exception policy.

There are three main scenarios in which you may need to handle exceptions. The most common is the first of these

Handling All Exceptions in a Catch Section

You can save considerable time and effort when implementing this common scenario by using the Process method of the Exception Handling Application Block to execute the code that does the work, and leave it to the block to handle any exception that may occur.

public class MyClass
{
 private ExceptionManager exManager;

 public MyClass(ExceptionManager exceptionManager)
 {
 exManager = exceptionManager;
 }

 public void ProcessActionMethod()
 {
 exManager.Process(MyActionMethod, "MyExceptionPolicy");
 }

 private void MyActionMethod()
 {
 // ... code here to carry out the application tasks ...
 }
}

To execute a routine that does accept parameters but does not return a value:

exManager.Process(() => method-name(param1, param2),
 "Exception Policy Name");

To execute a routine that accepts parameters and returns a value:

var result = exManager.Process(() => method-name(param1, param2),
 "Exception Policy Name");

To execute a routine that accepts parameters and returns a value, and supply a default value to be returned should an exception occur (and if the policy that executes does not throw the exception). If you do not specify a default value and the Post Handling Action is set to None, the Process method will return null (C#) or Nothing (Visual Basic) for reference types, zero for numeric types, or the default empty value for other types should an exception occur.

var result = exManager.Process(() => method-name(param1, param2),
 default-result-value,
 "Exception Policy Name");

Designing Data Tier Components and Passing Data Through Tiers

Mapping Relational Data to Business Entities
Implementing Data Access Logic Components
Implementing Business Entities
Transactions
Validations
Exception Management
Authorization and Security
Deployment

For more information, see the following Microsoft® patterns & practices guides:

Exception Management

When errors occur in .NET applications, the general advice is to throw exceptions rather than return error values from your methods. This advice has implications for the way you write data access logic components and business entity components. There are two general kinds of exceptions that will occur:

  • Technical exceptions, which include:
    • ADO.NET
    • Connection to database
    • Resources (such as database, network share, and Message Queuing) are unavailable
  • Business logic exceptions, which include:
    • Validation errors
    • Errors in stored procedures that implement business logic

Recommendations for Managing Exceptions in a Data Access Logic Component

public class CustomerDALC
{
  public void UpdateCustomer(Dataset aCustomer)
  {
    try
    {
      // Update the customer in the database...
    }
    catch (SqlException se)
    {
      // Catch the exception and wrap, and rethrow
      throw new DataAccessException("Database is unavailable", se);
    }
    finally
    {
      // Cleanup code
    }
  }
}

Recommendations for Using Manual Transactions in Data Access Logic Components

When you implement manual transactions in data access logic components, consider the following recommendations:

  • Where possible, perform your processing in stored procedures. Use the Transact-SQL statements BEGIN TRANSACTION, END TRANSACTION, and ROLLBACK TRANSACTION to control transactions. For a code example, see “How To Perform Transactions With Transact-SQL” in the .NET Data Access Architecture Guide.
  • If you are not using stored procedures, and the data access logic components will not be called from a business process, you can control transactions programmatically by using ADO.NET. For a code example, see “How to Code ADO.NET Manual Transactions” in the .NET Data Access Architecture Guide.


Filed under: .NET, Architecture, ASP.NET, Database, Design, Patterns, Reference Tagged: ADO.NET, Arch, Architect, Architecture, BDAL, Blocks, Concurrency, DAL, Database, Dataset, DB, Decisions, Design, EF4, Entity, EntLib, Error Handling, Errors, Exceptions, Format, Interfaces, JSON, Layers, Logging, Patterns, SCL, Services, Text, Tiers, Transactions, XML

Written by Visitor Blogs on May 25th, 2010 with 1 comment.
Read more articles on Concurrency and EntLib and Transactions and Interfaces and Logging and Arch and Dataset and DAL and JSON and SCL and Error Handling and Blocks and BDAL and Layers and EF4 and Entity and Tiers and ADO.NET and exceptions and Database and Format and XML and services and ASP.NET and Design and errors and otherSoftware and Patterns and Architect and DB and Architecture and reference and Decisions and Text and .Net.

Tips, Tricks, Notes on Entity Frameworks 4.0

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

Written by Visitor Blogs on May 20th, 2010 with no comments.
Read more articles on Frameworks and Entity and EF4 and ADO.NET and ASP and RIA and data Access and Data Services and OData and reference and SQL Server and SQL and ASP.NET and .Net and Code and WCF and feeds and otherSoftware and Database and c# and RSS.

Programming Entity Framework

Building Data Centric Apps with the ADO.NET Entity Framework

By
Julia Lerman

Examples

http://apress.com/book/view/1430227036

Source Code

http://rapidshare.com/files/267643644/Wrox.Professional.ADO.NET.3.5.with.LINQ.and.the.Entity.Framework.Feb.2009.rar

Source Code ::

http://apress.com/book/view/9781590599907

I’ve been using a lot of NoTracking queries to grab lists of data that I don’t need change tracked. One of the interesting behaviors of EF4’s Lazy Loading is that even if you have entities that you have queried with NoTracking on, they will still lazy load related entities.

http://learnentityframework.com/

SELECT VALUE BAModel.Contact(c.ContactID,c.FirstName,c.LastName,c.Title,c.AddDate,c.ModifiedDate)
FROM dbo.Contact as c
WHERE c.AddDate>=”1/1/2007″

I was trying to emulate T-SQL here but I need a date, not a string. I thought that without a function I was hosed again, until I discovered Entity SQL’s Literals and rewrote the query successfully this way.

SELECT VALUE BAModel.Contact(c.ContactID,c.FirstName,c.LastName,c.Title,c.AddDate,c.ModifiedDate)
FROM dbo.Contact as c
WHERE c.AddDate>= DATETIME’2007-01-1 00:00′

I’ve had  number of emails recently with people using Entity SQL and having problems similar to this, most commonly with decimals & doubles (e.g., 123.24). First I will point you to the MSDN documentation page on Literals for Entity SQL.

this ESQL expression will fail:

select p.amount from BAEntities.Payments as p where p.amount=125.25

The exception message is “The argument types ‘Edm.Decimal’ and ‘Edm.Double’ are incompatible for this operation. Near WHERE predicate, line 1, column 61.

Entity Framework POCO Template for .NET 3.5

Funky Behavior NoTracking Query Entities

Entity Framework Profiler’s Beta period ends tomorrow when it goes RTM. But that means the 30% discount also ends. It will go from $220US to $315US tomorrow.

I spend a lot of time looking at what’s going on in my database when using EF and the views that EFProf provide are indispensible. It’s organized by context instance and provides links back to the .NET code that executed each command.

  1. Agile Entity Framework 4 Repository: Part 1- Model and POCO Classes
  2. Agile Entity Framework 4 Repository: Part 2- The Repository
  3. Agile EF4 Repository: Part 3 -Fine Tuning the Repository
  4. Agile EF4 Repository: Part 4: Compiled LINQ Queries
  5. Agile Entity Framework 4 Repository Part 5: IObjectSet and Include
  6. Agile Entity Framework 4 Repository: Part 6: Mocks & Unit Tests

Data Access

Entity Framework Lazy Loading by Context or by Property?

Defining Constraints in an EF4 model that don’t exist in the database

Entity Framework ObjectContext and Reporting

,

1.
Chapter 1 Introducing the ADO.NET Entity Framework
1.
Programming Against a Model, Not Against the Database
2.
The Entity Data Model: A Client-Side Data Model
3.
The Entity in “Entity Framework”
4.
Choosing Your Backend
5.
Entity Framework Features
6.
The Entity Framework in Web Services
7.
What About ADO.NET DataSets and LINQ to SQL?
8.
Entity Framework Pain Points
9.
Programming the Entity Framework
2.
Chapter 2 Exploring the Entity Data Model
1.
Why Use an Entity Data Model?
2.
The EDM Within the Entity Framework
3.
Your First EDM
4.
The EDM in the Designer Window
5.
Entity Properties
6.
The Naked Model: Inspecting the Model’s XML
7.
A Less Daunting Model View
8.
The Three Parts of the Model
9.
CSDL: The Conceptual Schema
10.
SSDL: The Store Schema
11.
MSL: The Mappings
12.
Database Views in the EDM
13.
Code Generation from EDM to Classes
14.
Summary
3.
Chapter 3 Querying Entity Data Models
1.
Query the Model, Not the Database
2.
Your First EDM Query
3.
LINQ to Entities Queries
4.
Entity SQL Queries That Return Objects
5.
Method-Based Syntax Queries for LINQ and Entity SQL
6.
The Shortest Query
7.
EntityClient: The Lowest-Level Method for Returning Streamed Data Through EDM Queries
8.
Translation to Database Queries
9.
Avoid Inadvertent Query Execution
10.
Summary
4.
Chapter 4 Exploring EDM Queries in Greater Depth
1.
Same Model, Friendlier Name
2.
Projections in Queries
3.
Projections in Entity SQL
4.
Querying Across Associations
5.
Joins and Nested Queries
6.
Grouping
7.
Shaped Data Returned by Queries
8.
Deferred Loading and Eager Loading Queries
9.
Retrieving a Single Entity
10.
Retrieving a Single Entity with GetObjectByKey
11.
Entity SQL’s Wrapped and Unwrapped Results
12.
Summary
5.
Chapter 5 Modifying Entities and Saving Changes
1.
How ObjectContext Manages Entities
2.
The SaveChanges Method
3.
Adding New Entities
4.
Inserting New Parents and Children
5.
Deleting Entities
6.
Summary
6.
Chapter 6 Using Stored Procedures with the EDM
1.
Adding the Stored Procedures into the Model
2.
Working with Functions
3.
Implementing Functions
4.
The EDM Designer’s Model Browser
5.
Mapping the Last of the Four Functions: CustomersbyState
6.
More About the Update Model Wizard
7.
Summary
7.
Chapter 7 Tuning Up a Model
1.
The BreakAway Geek Adventures Business Model
2.
Creating a Class Library Project to Host an EDM
3.
Inspecting and Cleaning Up a New Model
4.
Cleaning Up Navigation Property Names
5.
Mapping a Few Stored Procedures
6.
Working with Many-to-Many Relationships
7.
Building the BreakAwayModel Project
8.
Summary
8.
Chapter 8 Data Binding with Windows Forms and WPF Applications
1.
Data Binding with Windows Forms Applications
2.
Data Binding with WPF Applications
3.
Summary
9.
Chapter 9 Working with Object Services
1.
Where Does Object Services Fit into the Framework?
2.
Query Processing
3.
Object Materialization
4.
The ObjectContext
5.
State Management and ObjectStateEntry
6.
Relationship Management
7.
Sending Changes Back to the Database
8.
Additional Features
9.
Summary
10.
Chapter 10 Customizing Entities
1.
Partial Classes
2.
Customizable Methods
3.
Customizable Event Handlers
4.
Other Opportunities for Customization
5.
Summary
11.
Chapter 11 Using the ASP.NET EntityDataSource Control
1.
Getting to First Base with the EntityDataSource Control and Flat Data
2.
Understanding How the EntityDataSource Is Able to Retrieve and Update Your Data
3.
Working with Related EntityReference Data
4.
Working with Hierarchical Data in a Master/Detail Form
5.
Browsing Through the EntityDataSource Events
6.
Summary
12.
Chapter 12 Customizing Entity Data Models
1.
Designer Support for Mappings
2.
Mapping Table per Type Inheritance for Tables That Describe Derived Types
3.
Using Entity Splitting to Map a Single Entity to More Than One Table
4.
Using Conditional Mapping to Filter Entity Mappings
5.
Implementing Table per Hierarchy Inheritance for Tables That Contain Multiple Types
6.
Implementing Customizations That Are Not Supported by the EDM Designer
7.
Mapping Table per Concrete (TPC) Type Inheritance for Tables with Overlapping Fields
8.
Creating Complex Types to Encapsulate Sets of Properties
9.
Using QueryView to Create Read-Only Entities and Other Specialized Mappings
10.
Additional Customization Options
11.
Summary
13.
Chapter 13 Working with Stored Procedures When Function Mapping Won’t Do
1.
Does the Procedure Line Up with an Entity?
2.
Overview of Procedures, UDFs, and TVFs in the EDM
3.
Composing Queries Against Functions
4.
Mapping and Executing Query Stored Procedures
5.
Adding Native Queries to the Model
6.
Adding Native Views to the Model
7.
Using Commands That Affect the Persisted Database
8.
Defining Insert, Update, and Delete Stored Procedures Directly in the Model
9.
Mapping Insert/Update/Delete to Types Within an Inheritance Structure
10.
Implementing and Querying with User-Defined Functions (UDFs)
11.
Summary
14.
Chapter 14 Using Entities with Web and WCF Services
1.
Building a Client That Is Ignorant of the Entity Framework
2.
Using the Entity Framework with ASMX Web Services
3.
Using the Entity Framework with WCF Services
4.
Summary
15.
Chapter 15 Working with Relationships and Associations
1.
Deconstructing Relationships in the Entity Data Model
2.
Deconstructing Relationships Between Instantiated EntityObjects
3.
Defining Relationships Between Entities
4.
Learning a Few Last Tricks to Make You a Relationship Pro
5.
Summary
16.
Chapter 16 Making It Real: Connections, Transactions, Performance, and More
1.
EntityConnection and Database Connections in the Entity Framework
2.
The Entity Framework and Transactions
3.
The Entity Framework and Security
4.
The Entity Framework and Performance
5.
Entities in Multithreaded Applications
6.
Summary
17.
Chapter 17 Controlling Objects with ObjectStateManager and MetadataWorkspace
1.
Managing ObjectStateEntry Objects with ObjectStateManager
2.
Getting an ObjectStateManager and Its Entries
3.
CurrentValues and OriginalValues
4.
Building the ObjectStateEntry Visualizer
5.
ObjectStateManager and SavingChanges
6.
The MetadataWorkspace API
7.
Creating EntityObjects Without Entity Classes
8.
Creating Entities and Graphs Dynamically
9.
Summary
18.
Chapter 18 Handling Entity Framework Exceptions
1.
Preparing for Exceptions in Entity Framework Code
2.
EntityConnectionString Exceptions
3.
Query Compilation Exceptions
4.
Creating a Common Wrapper to Handle Query Execution Exceptions
5.
SaveChanges Command Execution Exceptions
6.
ObjectStateEntries Returned by Object Services Exceptions
7.
InvalidOperationExceptions
8.
Exceptions When Multiple Parties Edit Data Concurrently
9.
Understanding Optimistic Concurrency Options in the Entity Framework
10.
Implementing Optimistic Concurrency with the Entity Framework
11.
Handling OptimisticConcurrencyExceptions
12.
Handling Concurrency Exceptions at a Lower Level
13.
Handling Exceptions When Transactions Are Your Own
14.
Summary
19.
Chapter 19 Using Your Own Custom Classes
1.
Mapping Classes to the Entity Data Model
2.
Implementing the IPOCO Interfaces
3.
Custom Class Assemblies and Entity Data Model Files
4.
Summary
20.
Chapter 20 Using the Entity Framework in n-Tier Client-Side Applications
1.
Thinking in Layers
2.
Finding Your Motivation: A Master/Detail Data Entry Form That Will Use the DataBridge Class
3.
Preventing Non-UI Logic from Leaking into the UI
4.
Implementing Logic That Fits Best in the Entity Partial Classes
5.
Building the CommandExecutor Class
6.
Building the DataBridge Class
7.
Using the DataBridge Class for Data Binding in a Master/Detail Form
8.
Allowing Users to Roll Back Their Edits
9.
Helping the User Who Forgets to Save Changes
10.
Summary
21.
Chapter 21 Using the Entity Framework in n-Tier ASP.NET Applications
1.
Understanding How an ObjectContext Fits into the Web Page Life Cycle
2.
Introducing ASP.NET’s ObjectDataSource Control
3.
Designing Object Provider Classes to Be Used with an ObjectDataSource
4.
Wiring Up the Provider Classes to ObjectDataSource Controls
5.
Understanding Why We Didn’t Use Object Graphs in This Business Layer
6.
Summary
22.
Chapter 22 Implementing a Smarter WCF Service for Working with Entities
1.
Will Your Client Agree to Your Data Contract?
2.
Shipping DTOs, Not EntityObjects
3.
Creating EntityState Properties That Do Not Rely on ObjectContext
4.
Designing the Service Interface
5.
Implementing the Service Operations
6.
Implementing the Client That Will Use the WCF Service
7.
Testing It All with a Simple Console Application
8.
Summary
23.
Chapter 23 The Entity Framework, Today and Tomorrow
1.
What About Building Reports with the Entity Framework?
2.
Extensions, Samples, and Solutions from Microsoft
3.
Entity Framework v.Next
4.
Blogs, Forums, and Other Resources

1.
Appendix Entity Framework Assemblies and Namespaces
1.
Unpacking the Entity Framework Files
2.
Exploring the Namespaces


Filed under: .NET, Blogs, Code, Database, Design, Products, Reference Tagged: .NET, ADO.NET, Books, DAO, Data, DTO, EF4, Entity, Entity Frameworks, Linq, ODBC, Oracle, SQL

Written by Visitor Blogs on May 20th, 2010 with no comments.
Read more articles on Entity and EF4 and ADO.NET and reference and Data and ODBC and Entity Frameworks and DTO and DAO and LINQ and books and .Net and Blogs and Code and SQL and Oracle and otherSoftware and Database and Design and Products.