entity framework, linq and model-first for the oracle database

26
7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 1/26 Print Preview Entity Framework, LINQ and Model- First for the Oracle Database This tutorial contains the follow ing sections: Purpose Time to Complete Overview Prerequisites Creating a new Project in Visual Studio Creating an Oracle Connection Creating an Entity Data Model using the Entity Data Model Wizard Entity Framew ork Data Retrieval Function Imports and Retrieving Implicit Resultsets | Inserting and Updating Data Directly Retrieving Output Parameters from Stored Procedures Insert and Delete Data Using LINQ Model-First Summary Viewing Screenshots Click icon to show all screenshots Note: Alternatively, you can click an individual icon (or image) associated w ith each step to view (or hide) the screenshot associated w ith that step. Entity Framework, LINQ and Model-First for the Oracle Database Purpose This tutorial covers how to use Entity Framework, Language Integrated Query (LINQ), and generate Data Definition Language (DDL) scripts using Model-First for Oracle database. Time to Complete Approximately 30 mins Overview Microsoft Entity Framework abstracts the relational, logical database schema and presents a conceptual schema to the .NET application. It provides object-relational mapping for .NET developers. LINQ is a .NET data querying language which can query a multitude of data sources, one of which are entities via LINQ to Entities. Model-First allows the conceptual model to be created first by the developer. Next, Visual Studio can create Oracle DDL scripts to generate the relational database model based on the conceptual model. In this tutorial, you will learn how to use Oracle Database and these three technologies with Microsoft Visual Studio and Oracle Data Provider for .NET (ODP.NET). You will start by creating an Entity Data Model (EDM) from an existing Oracle Database schema using Entity Data Model Wizard. Then, you will query the EDM using three different methods: 1. LINQ query 2. LINQ query with a lambda expression and calling a stored procedure to perform an update against the results 3. Entity SQL Next, you will call a stored procedure added to the EDM via a function import. The stored procedure will modify the database data and return the results with an implicit resultset. To return the resultset, you will provide the resultset parameter information in a .NET config file. You will then insert and delete data to the database without using a stored procedure. Lastly, you will show how to use Model-First with Oracle database. In a Model-First scenario, a developer first creates an Entity Framework object-relational data model. From that data model, the developer can automatically generate an Oracle relational database model in the form of DDL scripts. Prerequisites Before starting this tutorial, you should: 1. Install Microsoft Visual Studio 2010 with .NET Framework 4 or higher. 2. Install Oracle Database 10.2 or later or Oracle Database XE. 3. Install Oracle Data Access Components (ODAC) 11.2.0.3 or later from OTN. The ODAC download includes Oracle Developer Tools for Visual Studio and ODP.NET that will be used in this lab. 4. Extract these files into your working directory. Creating a new Project in Visual Studio 1. To create a new .NET console application to run Entity Framework and LINQ application form, open Visual Studio. Click File. Select New > Project. 2. Select Visual C#:Windows > Console Application. Rename the project as EntityFramework. Click OK.

Upload: fromac5969

Post on 27-Dec-2015

66 views

Category:

Documents


0 download

DESCRIPTION

For Entity Framwrok

TRANSCRIPT

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 1/26

Print Preview

Entity Framework,

LINQ and Model-

First for the Oracle

Database

This tutorial contains the

follow ing sections:

Purpose

Time to Complete

Overview

Prerequisites

Creating a new Project in

Visual Studio

Creating an Oracle

Connection

Creating an Entity Data

Model using the Entity Data

Model Wizard

Entity Framew ork Data

Retrieval

Function Imports and

Retrieving Implicit

Resultsets | Inserting and

Updating Data Directly

Retrieving Output

Parameters from Stored

Procedures

Insert and Delete Data

Using LINQ

Model-First

Summary

ViewingScreenshots

Click icon to show

all screenshots

Note: Alternatively, you can

click an individual icon (or

image) associated w ith each

step to view (or hide) the

screenshot associated w ith

that step.

Entity Framework, LINQ and Model-First for the Oracle Database

Purpose

This tutorial covers how to use Entity Framework, Language Integrated Query (LINQ), and generate Data Definition Language (DDL)scripts using Model-First for Oracle database.

Time to Complete

Approximately 30 mins

Overview

Microsoft Entity Framework abstracts the relational, logical database schema and presents a conceptual schema to the .NET

application. It provides object-relational mapping for .NET developers.

LINQ is a .NET data querying language which can query a multitude of data sources, one of which are entities via LINQ to Entities.

Model-First allows the conceptual model to be created first by the developer. Next, Visual Studio can create Oracle DDL scripts to

generate the relational database model based on the conceptual model.

In this tutorial, you will learn how to use Oracle Database and these three technologies with Microsoft Visual Studio and Oracle Data

Provider for .NET (ODP.NET). You will start by creating an Entity Data Model (EDM) from an existing Oracle Database schema using

Entity Data Model Wizard. Then, you will query the EDM using three different methods:

1. LINQ query

2. LINQ query with a lambda expression and calling a stored procedure to perform an update against the results

3. Entity SQL

Next, you will call a stored procedure added to the EDM via a function import. The stored procedure will modify the database data

and return the results with an implicit resultset. To return the resultset, you will provide the resultset parameter information in a .NET

config file. You will then insert and delete data to the database without using a stored procedure.

Lastly, you will show how to use Model-First with Oracle database. In a Model-First scenario, a developer first creates an Entity

Framework object-relational data model. From that data model, the developer can automatically generate an Oracle relational

database model in the form of DDL scripts.

Prerequisites

Before starting this tutorial, you should:

1. Install Microsoft Visual Studio 2010 with .NET Framework 4 or higher.

2. Install Oracle Database 10.2 or later or Oracle Database XE.

3. Install Oracle Data Access Components (ODAC) 11.2.0.3 or later from OTN. The ODAC download includes Oracle

Developer Tools for Visual Studio and ODP.NET that will be used in this lab.

4. Extract these files into your working directory.

Creating a new Project in Visual Studio

1. To create a new .NET console application to run Entity Framework and LINQ application form, open Visual Studio.

Click File. Select New > Project.

2. Select Visual C#:Windows > Console Application. Rename the project as EntityFramework. Click OK.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 2/26

3. The project EntityFramework opens up.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 3/26

Creating an Oracle Connection

Before creating the Entity Data Model, you need an Oracle database connection that uses ODP.NET. To create an OracleConnection:

1. Select View > Server Explorer.

2. In the Server Explorer window, if you already have a HR schema connection, expand it to connect to the database.

As an example, the screen shot below identifies the HR schema as HR.ORCL. Enter HR for the User name and a

password and click OK. Skip to Step 6.

3. If you do not have a HR connection, then right-click on Data Connections in Server Explorer. Choose Add

Connection and select a Data source name with the HR schema, such as ORCL. Enter HR for the User name and

a Password. Check Save password. Select Default as the Role and click Test Connection.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 4/26

4. Click OK in the "Test connection succeeded" dialog box.

5 . The connection has been created. Expand HR.ORCL

6 . You will now create the stored procedures that will be used later in this lab to perform updates and data retrieval.

To add the stored procedures into the HR.ORCL data connection, right-click HR.ORCL and select Query Window.

7 . Open the working directory to where you extracted the files.zip. Find the INCREASE_SALARY_BY_10,

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 5/26

UPDATE_AND_RETURN_SALARY and OUTPARAM stored procedures. Copy the code for

INCREASE_SALARY_BY_10, UPDATE_AND_RETURN_SALARY and OUTPARAM into the SQL Query Window and

click Execute Query ( )for each of the stored procedures.

8 . Make sure that the newly added stored procedures appear beneath the HR.ORCL > Procedures node.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 6/26

Creating an Entity Data Model using the Entity Data Model Wizard

You are now ready to create our Entity Data Model based on HR's DEPARTMENTS and EMPLOYEES tables and the three newstored procedures that you just added. To do so, you will add an EDM to our project. The EDM will be automatically generated using

the Entity Data Model Wizard.

1. In the Solution Explorer window, right-click the EntityFramework project and select Add > New Item.

2. In the Add New Item window, choose ADO.NET Entity Data Model and rename it to HRModel.edmx and click Add.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 7/26

3 . In the Entity Data Model Wizard, select Generate from database and click Next.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 8/26

4 . Select HR.ORCL as the data connection. Select "Yes, include the sensitive data in the connection string" and

name it as HREntities and click Next.

5. Select DEPARTMENTS and EMPLOYEES from Tables and INCREASE_SALARY_BY_10 ,

UPDATE_AND_RETURN_SALARY and OUTPARAM from Stored Procedures and click Finish.

Note: If these stored procedures do not appear, make sure that you added them earlier in the OBE -INCREASE_SALARY_BY_10, UPDATE_AND_RETURN_SALARY and OUTPARAM in the HR schema under

Procedures.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 9/26

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 10/26

6. The HRModel EDM has been created and is displayed.

Entity Framework Data Retrieval

There are a number of ways to query the EDM, which then retrieves data from the database. This section will demonstrate three

common EDM querying methods: LINQ, LINQ with lambda expressions, and Entity SQL.

1. Executing a LINQ query

To execute a LINQ query against an Oracle database, you will add a reference to an Entity Framework assembly. You will thencreate the code to execute a LINQ query and return the results to the console window.

1. In the Solution Explorer window, right-click References and select Add Reference.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 11/26

2. On the .NET tabbed page, select System.Data.Entity version 4 assembly and click OK.

3. Type the namespace references highlighted in the graphic below. Alternatively, you can copy and paste this

information. Open the files folder containing Programcs.txt from your working directory. Then, copy the codeincluding the namespace references and paste them at the top of the Program.cs.

These directives allow access to the ADO.NET, Entity Framework and Object Services namespaces. It is not

necessary to reference ODP.NET namespaces in this tutorial as ODP.NET is being used indirectly via EntityFramework.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 12/26

4. Type in the .NET code below. The code executes a LINQ query against the EDM you just created. It then accesses

the result and outputs it to the screen. The LINQ query retrieves all employee information with EMPLOYEE_ID lessthan the max_id variable.

Alternatively, you can copy the code from Programcs.txt for the LINQ query and paste it on Program.cs after the

Main statement. Make sure you include an end curly brace to terminate the USING scope.

Click (Start debugging).

5. The output of the LINQ query appears, thereby successfully executing a LINQ query against the Oracle database.

2. Executing a LINQ query using a lambda expression and Entity Framework stored procedure

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 13/26

mapping

LINQ queries can include lambda expressions. Lambdas are used as LINQ arguments to standard query operator methods.

Updates, inserts, and deletes can be executed on an entity by mapping Oracle stored procedures to these operations in the EDM.

In this portion of the lab, you will execute a LINQ query with a lambda expression against the EMPLOYEE entity, then map a stored

procedure to execute an update against all rows selected. You will use one of the stored procedures you imported earlier into the

EDM.

1.First, you will create a stored procedure mapping for updating the data. When .NET tries to update the data, the mapped stored procedure every row selected by LINQ.

In the Solution Explorer window, select HRModel.edmx and click Model Browser.

2. In the HRModel.edmx, right-click on EMPLOYEE entity and select Stored Procedure Mapping.

3. In the Mapping Details - EMPLOYEE, select ,<Select Update Function> and select the stored procedure, INCREASE_SALARY_BY_10

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 14/26

4.Parameter data types must now be mapped between the entity and Oracle database. Select EMPLOYEE_ID for ID and SALARY for SALdown lists.

5.Type in the highlighted code below or copy the code from the Programcs.txt from the section labeled "LINQ using lambda expressions --"

in Program.cs after the previous code statements. Click (Start Debugging)

In the application, you will notice that the result.SALARY is set to 18000. Under the covers, Entity Framework is executing the stored procedure

The salary is set to 18000, then increased by 10 in the stored procedure, providing custom logic in addition to the default behavior. In the next section,you will query these same rows to demonstrate the salaries have indeed been set to 18010. You may define your own stored procedures to override

default behavior.

Note: Press Enter to continue after viewing the first resultset.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 15/26

6.LINQ retrieves the two rows of data and updates each row by executing the stored procedure. You should see text that indicates the salaries have been

updated.

3. Executing an Entity SQL query

In this section, you will query the same rows as in the previous section to show that the stored procedure successfully updated the

selected rows. You will query using another query method available in Entity Framework called Entity SQL.

1.Type the highlighted code below or copy code from Programcs.txt from the section labeled "Entity SQL -- "and

paste it in Program.cs after the previous code statements. Click (Start Debugging) to view the updated results

with the salaries increased by 10.

Note: Press Enter twice to continue while viewing the output.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 16/26

Function Imports and Retrieving Implicit Resultsets | Inserting and Updating Data Directly

Entity Framework allows developers to define their own .NET methods to execute database stored procedures. This is done by

creating function imports in the conceptual model that map to stored procedures. In this section, you will define your own method

that is mapped to an Oracle stored procedure, which performs an update. The stored procedure will also return the modified datausing an implicit resultset. The resultset metadata is defined by the developer in a .NET config file so that Entity Framework can

properly retrieve the data.

This section shows how to modify Oracle database data programmatically in Entity Framework. You will perform an insert and adelete on the DEPARTMENTS table.

1. You will use Visual Studio's Function Import tool to map the stored procedure to a user-defined .NET method.

Since the stored procedure returns an implicit resultset, you need to define the resultset metadata in the .NET

config file before using the tool.

In the Solution Explorer window, open the App.Config file.

2. From the working directory where you extracted the files.zip, find the AppConfig.txt file and open it. Copy code for

<oracle.dataaccess.client> section and paste it below the </connectionStrings> tag in the App.Config file. Now,

you have defined the metadata for retrieving the stored procedure resultset. Here, the required attributes that mustbe defined for scalar data columns include: Column Name, Native Oracle Data Type, and Provider Type. This is

seen in the SALARY column attributes in the config. Additional attributes are optional for scalar columns. The

FIRST_NAME column shows some of these optional attributes.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 17/26

3. Next, you will use the Function Import tool to map a .NET method to an Oracle stored procedure. Double-clickHRModel.edmx and select Model Browser.

4. In the Model Browser, expand the HRModel.Store, then expand the Stored Proceduresnode. Select the

UPDATE_AND_RETURN_SALARY procedure. You imported this procedure earlier when you created the EDM.

5. Right-click UPDATE_AND_RETURN_SALARY and select Add Function Import.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 18/26

6. In the Add Function Import window, select Complex in the "Returns a Collection Of" section. The stored

procedure returns a result set with two columns, not a fully-defined entity nor a scalar value.

Click Get Column Information. The column information will be retrieved from the .NET config file.

7. Click Create New Complex Type in the "Stored Procedure Column Information" section and click OK.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 19/26

To call the method from .NET, you will use the default UPDATE_AND_RETURN_SALARY Function Import name.

8. In the Model Browser, you will now see the UPDATE_AND_RETURN_SALARY under HRModel.edmx > HRModel >

EntityContainer: HREntities > Function Imports.

9. In the Solution Explorerwindow, open the Program.cs file. Type or copy the following code from the

Programcs.txt - "Update salary using a stored procedure function import" after the previous code statements.

Notice that the entity context now has an UPDATE_AND_RETURN_SALARY method defined. This method will callthe mapped stored procedure and return the implicit resulset.

Click (Start Debugging).

Note: Press Enter thrice to continue while viewing the resultset.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 20/26

10. The .NET method returns the employee name and updated salary.

Retrieving Output Parameters from Stored Procedures

This section demonstrates how to retrieve output parameters from stored procedures within Entity Framework. Output parameters

can be retrieved from a function import mapped to a stored procedure. The output parameter must be declared explicitly in .NET andmap to an output parameter in the function import definition.

1 . In the Model Browser, expand the HRModel.Store, then expand the Stored Procedures node. Select the

OUTPARAM procedure. You imported this procedure earlier when you created the EDM.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 21/26

2 . Right-click OUTPARAM and select Add Function Import.

3 . In the Add Function Import window, select None in the "Returns a Collection Of" section. The stored procedure

returns an output parameter, not a collection in this case. To call the method from .NET, you will use the defaultOUTPARAM Function Import name. Click OK.

4 . In the Solution Explorer window, open the Program.cs file. Type or copy the following code from the

Programcs.txt - "Retrieving output parameters from stored procedures" after the previous code statements.

Notice that the entity context now has an OUTPARAM method defined. An ObjectParameter is bound to theOUTPARAM method to retrieve the output parameter. This method will call the mapped stored procedure that

returns the parameter.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 22/26

Click (Start Debugging).

Note: Press Enter four times to continue while viewing the resultset.

Insert and Delete Data Using LINQ

This section demonstrates how LINQ can be used to insert and delete data programmatically.

1. Type or copy the code that inserts and deletes the new department entry in your Program.cs file. You can copy

from the Programcs.txt file and paste it to the Program.cs file after the previous code statements.

The program comments describe what each code segment does.

Click (Start Debugging).

Note: Press Enter five times to continue while viewing the resultset.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 23/26

The console will describe whether the department was successfully added and deleted.

Model-First

In this section, you will add a new property to the EMPLOYEE entity. To reflect the new property in the Oracle database schema as a

column, Visual Studio will generate Oracle DDL scripts from the new EDM. These scripts can then be run against the Oracle

database to update the relational model.

1. In the HRModel.edmx, select the EMPLOYEE entity.To create a new property in EMPLOYEE entity, right-click on it

and select Add > Scalar Property. Name the property as ADDRESS.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 24/26

2. To generate the DDL scripts, open the Properties window of HRModel. Change the Database Schema Name to

HR and select SSDLtoOracle.tt for the DDL Generation Template. Make sure that Generate Oracle via

T4(TPT).xaml is selected in the Database Generation Workflow property to ensure table per type DDL will be

generated.

These selections ensure that Oracle DDL is created for the HR schema where each type represents a separatedatabase table.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 25/26

3. Right-click HRModel.edmx and select Generate Database from Model.

4. After you select Generate Database from Model, a Custom Workflow Security Warning will appear since Oracledefines a custom workflow. Click OK.

7/7/2014 Entity Framework, LINQ and Model-First for the Oracle Database

http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm 26/26

5. The Generate Database Wizard generates DDL scripts for Oracle database to execute. These scripts can be

saved to a file to be run later, such as through the built-in SQL*Plus execution engine that is part of Oracle

Developer Tools for Visual Studio.

Note that the script creates and deletes database objects. By default, the delete scripts are commented out. If you

wish to use them, make sure to uncomment them before executing.

Summary

In this tutorial, you have learned how to:

Create a new Project in Visual Studio.

Create an Oracle connection.

Create an Entity Data Model using the Entity Data Model Wizard.

Execute queries for Entity Framework Data Retrieval.

Map stored procedures to EDMs.Use Entity Framework Function Imports for creating user-defined methods mapped to stored procedures.

Retrieve Output Parameters from Stored Procedures.

Programmatically modify Entity Framework data.

Use Model-First to generate Oracle DDL scripts.

Lead Curriculum Developer: Anupama Mandya

Other Contributors: Alex Keh

Copyright © 2011, Oracle and/or its affi l iates. All rights reserved