Quantcast Entity framework với stored procedure

Entity framework với stored procedure

by Neon Quach 23. January 2011 22:17

Entity framework support store procedure, tức là chúng ta có thể gọi store, exec trực tiếp và nhận kết quả trả về, chúng ta hãy bắt đầu với 1 ứng dụng console đơn giản nhé. CSDL mình chuẩn bị kết nối là Northwind và sẽ gọi store Get Ten Most Expensive Products.

Đầu tiên tạo 1 dự án Console named: EntityFrameworkStoredProc → Add item... → ADO.NET Entity Data model named: Nwind.edmx → Connect tới CSDL Northwind

Màng hình surface Entity Data Model Designer xuất hiện → Right click bất cứ chổ nào của màng hình surface chọn Add → Function Import....

Màng hình import xuất hiện:
Function Import name: GetTenExpProducts
Stored Procedure name: Ten_Most_Expensive_Products
Click vào button Create New Complete type
OK



Ở màng hình này chúng ta có thể import Function bao gồm stores procedure và user-defined functions và giá trị trả về có thể là Scalar (int,string...), Complex type hoặc 1 entity thậm chí không.

Giờ chúng ta look deep vào SSDL file generate function import

<Function Name="Ten_Most_Expensive_Products" Aggregate="false" BuiltIn="false" NiladicFunction="false" 
IsComposable="false" ParameterTypeSemantics="AllowImplicitConversion" StoreFunctionName="Ten Most Expensive Products" Schema="dbo" />

Các thuộc tính:
Name: Tên của function
Aggregate, BuiltIn và NiladicFunction luôn false khi nó là stored procedure (chỉ apply cho user define function)
NiladicFunction: function không có parameter
IsComposable: liệu chúng ta có thể sử dụng kết quả của function trong 1 query khác. (always false if stored procedure)
ParameterTypeSemantics: enum, "AllowImplicitConversion" nghĩa là các kiểu dữ liệu input được ngầm định chuyển đổi.
StoreFunctionName: tên của stored procedure...

Bắt đầu call stored:

using System;

namespace EntityFrameworkStoredProc
{
    class Program
    {
        static void Main()
        {
            using (NwindEntities context = new NwindEntities())
            {
                foreach (var item in context.GetTenExpProducts())
                {
                    Console.WriteLine(item.TenMostExpensiveProducts + "\t\t\t" + item.UnitPrice);
                }
            }
            Console.Read();
        }
    }
}


Press F5 và xem kết quả trả về

EntityFrameworkStoredProc.rar (32.73 kb)

Tags:


Categories: ado.net entity framework

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Powered by BlogEngine.NET 2.5.0.5 - Eco Theme by n3o Web Designers