2013년 8월 30일 금요일

저장프로시저와 함수 - LINQ

저장프로시저를 이용한 다중테이블 입력 방법
예 : Customers와 CustomersInfo 두 테이블 있고 회원가입시
       Customers에는 UserName, Password, Email을 입력하고
       CustomerInfo에는 FullName과 Customers에 Primary Key인 CustomerID를 입력한다면

DB에 Stored Procedure 생성

CREATE PROCEDURE [InsertCust]
@Username VARCHAR(10),
@Password CHAR(40),
@Email VARCHAR(100),
@Fullname NVARCHAR(10)
AS
DECLARE @CustomerID INT;
BEGIN TRY
    INSERT INTO [Customers] VALUES(@Username, @Password, @Email);
    SELECT @CustomerID = [CustomerID] FROM [Customers] WHERE [UserName] = @Username;
    INSERT INTO [CustomerInfo]([CustomerID], [FullName]) VALUES(@CustomerID, @Fullname);
END TRY

BEGIN CATCH
    RETURN ERROR_NUMBER()
END CATCH
GO

Entity설정

[Function(Name="dbo.InsertCust")]
public int InsertCust(
    [Parameter(Name="Username",DbType="VarChar(10)")] string username,
    [Parameter(Name="Password",DbType="Char(40)")]    string password,
    [Parameter(Name="Email",DbType="VarChar(100)")]   string email,
    [Parameter(Name="FullName",DbType="NVarChar(30)")]string fullname)
    {
        IExecuteResult result = this.ExecuteMethodCall(
        this,
        ((MethodInfo)(MethodInfo.GetCurrentMethod())),
        username, password, email, fullname);
    return ((int)(result.ReturnValue));
}

사용방법

CustomersEntity entity = new CustomersEntity(conn);
int insert = entity.InsertCust("tomebody", "han001122", "tome@naver.com", "Tome kim");
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

저장프로시저를 이용한 다중테이블 조회 방법
예 : CustomerInfo, Products, Orders 3개의 테이블이 있다고 가정
       CustomerInfo에서는 FullName,
       Products에서는 ProductName,
       Orders에서는 UnitPrice, Amount를 읽어온다.
       단 CustomerID, ProductID를 기준값으로

DB에 Stored Procedure 생성


CREATE PROCEDURE [SelectOrderInfo] @CustomerID INT, @ProductID INT
AS
    SELECT c.FullName, p.ProductName, o.Quantity, (o.Quantity * p.UnitPrice) AS [Amount]
    FROM [CustomerInfo] c
    JOIN [Orders] o
    On c.CustomerID = o.CustomerID
    JOIN [Products] p
    On o.ProductID = p.ProductID
    WHERE c.CustomerID = @CustomerID And o.ProductID = @ProductID
GO

Entity설정


[Function(Name="dbo.SelectOrderInfo")]
public ISingleResult<SelectOrderInfoResult> SelectOrderInfo(
    [Parameter(Name="CustomerID",DbType="Int")]int CustomerID,
    [Parameter(Name="ProductID",DbType="Int")]int ProductID)
{
    IExecuteResult result = this.ExecuteMethodCall(
        this,
        ((MethodInfo)(MethodInfo.GetCurrentMethod())),
        CustomerID, ProductID);
    return((ISingleResult<SelectOrderInfoResult>)(result.ReturnValue));
}

public partial class SelectOrderInfoResult
{
    [Column]public string FullName { get; set; }
    [Column]public string ProductName { get; set; }
    [Column]public int Quantity { get; set; }
    [Column]public int Amount { get; set; }
}
SelectProcedure entity = new SelectProcedure(conn);

Entity설정

ISingleResult<SelectOrderInfoResult> Result = entity.SelectOrderInfo(1, 1);
foreach (SelectOrderInfoResult item in Result)
{
    Console.WriteLine("{0}-{1}-{2}-{3}",
        rs.FullName,
        rs.ProductName,
        rs.Quantity,
        rs.Amount);
}

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
ISingleResult<TEntity> : 저장 프로시저의 실행 결과로 리턴되는 엔티티 클래스의 단일 결과집합을 가진다.

델리게이트와 익명 메서드

C#에서 델리게이트는 delegate라는 키워드를 통해 선언되며 리턴 타입과 파라미터도 가질 수 있다. 또한 new 연산자를 통해 인스턴스를 생성하여 사용된다. 델리게이트가 갖는 리턴 타입과 파라미터는 그가 처리하는 메서드에 종속적이다.
대리자는 메서드를 다른 메서드에 인수로 전달하는데 사용된다.

예
// Declare delegate -- defines required signature:
delegate double MathAction(double num);

class DelegateTest
{
    // Regular method that matches signature:
    static double Double(double input)
    {
        return input * 2;
    }

    static void Main()
    {
        // Instantiate delegate with named method:
        MathAction ma = Double;

        // Invoke delegate ma:
        double multByTwo = ma(4.5);
        Console.WriteLine(multByTwo);

        // Instantiate delegate with anonymous method:
        MathAction ma2 = delegate(double input)
        {
            return input * input;
        };

        double square = ma2(5);
        Console.WriteLine(square);

        // Instantiate delegate with lambda expression
        MathAction ma3 = s => s * s * s;
        double cube = ma3(4.375);

        Console.WriteLine(cube);
    }
}
예

List<int> list = new List<int>();
list.AddRange(new int[] { 100, 200, 300, 400, 500, 600 });
ICollection<int> result = list.FindAll(delegate(int item) { return item > 350; });
foreach (int a in result)
{
    Console.WriteLine(a);
}

제네릭 형식 정의와 사용

1. using System.Collections.Generic
2. 제한 사항과 제약 사항
   
- 제한사항 
  1. 제네릭이 적용된 클래스는 ContextBoundObject 클래스로부터 파생될 수 없다.
  2. 열거형에 사용될 수 없다.
  3. Replection을 이용해서 생성되는 동적 메서드는 제네릭 형식을 취할 수 없다.
 -제약사항 : 제네릭 클래스 레벨에서 선언될 경우 선언하는 클래스에 몇 가지의 제약 사ㅏ항을 지정할 수 있다.  이 제약 사항은 SQL문에서 where절에서 사용하는 것과 의미가 동일하다.
예 :

//IDisposable을 구현하는 T
class GenericConstraint<T> where T : IDisposable{}
//class 타입 T, 구조체 타입 U
class GenericConstraint<T, U> where T : class where U : struct{}
//IComparable을 구현하고, 파라미터가 없는 기본 생성자를 가진 타입 T
class GenericConstraint<T> where T : IComparable, new()

//델리게이터에 파라미터가 없는 기본생성자를 가진 타입 T
delegate T GenericDelegate<T>(T val) where T : new();

Dictionary<TKey, TValue>
Dictionary<int, string> colorDic = new Dictionary<int, string>();
//key와 value를 쌍으로 저장
colorDic.Add(1, "Red");
//값 변경
colorDic[1] = "Black";
//key가 3인 color 값 조회
string blackColor = string.Empty;
if(colorDic.TryGetValue(3, out blackColor))
{
    Console.WriteLine("key가 3으로 저장된 Color는 {0}", blackColor);
}
//key가 4인 데이터 존재 유무 확인
if(!colorDic.ContainsKey(4))
{
    colorDic.Add(4, "Yellow");
}
//key값만 가지는 컬렉션 객체 생성
Dictionary<int, string>.KeyCollection keyCollection = colorDic.Keys;
foreach(int key in keyCollection)
{
    Console.WriteLine(key);
}
//value값만 가지는 컬렉션 객체 생성
Dictionary<int, string>.ValueCollection valueCollection = colorDic.Values;
//key와 value를 쌍으로 가지는 컬렉션의 요소 조회
foreach(KeyValuePair<int, string> keyValue in colorDic)
{
    Console.WriteLine("key {0}의 Color는 {1}", keyValue.Key, keyValue.Value); 
}
*TryGetValue 메서드는 key값을 기준으로 해당 데이터를 out파라미터로 전달한다.
List<T>
예:
List<int> list = new List<int>();
list.Add(100);
//컬렉션의 현재 배열 크기 조회
Console.WriteLine("컬렉션의 현재 배역 크기는 {0}", list.Capacity);
//컬렉션의 현재 저장 데이터 개수 조회
Console.WriteLine("컬렉션에 저장된 요소의 개수는 {0}", list.Count);
//1번째에 데이터 저장
list.Insert(1, 500);
//1번째에 저장된 데이터 조회
Console.WriteLine("1번째 데이터는 {0}", list[1]);
//1번째에 데이터 삭제
list.RemoveAt(1);
//컬렉션의 배열 크기를 조정
list.TrimExcess();
TrimExcess() : 동적 배열 크기를 갖는 클래스에서 공통적으로 사용되는 메서드로 호출후의 배열 크기는 컬렉션에 저장되어 있는 요소의 개수와 동일해 진다.
SortedList<TKey, TValue>
예:
// 컬렉션 인스턴스 생성
SortedList<int, string> colorSort = new SortedList<int, string>();
// 데이터 저장
colorSort.Add(1, "Red");
colorSort.Add(3, "Green");
colorSort.Add(2, "Blue");
// 저장된 데이터 조회
foreach (KeyValuePair<int, string> color in colorSort)
{
    Console.WriteLine(color.Value);
}
// 컬렉션의 배열 크기 조회
Console.WriteLine("현재 컬렉션의 배열 크기 : {0}", colorSort.Capacity);
// 컬렉션 배열 크기 조정
colorSort.TrimExcess();
// 첫 번째 배열 크기 및 요소 개수 조회
Console.WriteLine("첫 번째 TrimExcess 호출 후 컬렉션 배열 크기:{0}, 요소 개수:{1}", colorSort.Capacity, colorSort.Count);
// key 값이 2인 데이터 삭제
colorSort.RemoveAt(2);
// 컬렉션 배열 크기 조정
colorSort.TrimExcess();
// 두 번째 배열 크기 및 요소 개수 조회
Console.WriteLine("두 번째 TrimExcess 호출 후 컬렉션 배열 크기:{0}, 요소 개수:{1}", colorSort.Capacity, colorSort.Count );

LinkedList<T>
Queue<T>
Stack<T>