참고 URL

http://msdn.microsoft.com/ko-kr/library/bb386944.aspx

 

 

직접실행

string connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\northwind.mdf;
    Integrated Security=True; Connect Timeout=30; User Instance=True";
SqlConnection nwindConn = new SqlConnection(connString);
nwindConn.Open();

Northwnd interop_db = new Northwnd(nwindConn);

SqlTransaction nwindTxn = nwindConn.BeginTransaction();

try
{
    SqlCommand cmd = new SqlCommand(
        "UPDATE Products SET QuantityPerUnit = 'single item' WHERE ProductID = 3");
    cmd.Connection = nwindConn;
    cmd.Transaction = nwindTxn;
    cmd.ExecuteNonQuery();

    interop_db.Transaction = nwindTxn;

    Product prod1 = interop_db.Products
        .First(p => p.ProductID == 4);
    Product prod2 = interop_db.Products
        .First(p => p.ProductID == 5);
    prod1.UnitsInStock -= 3;
    prod2.UnitsInStock -= 5;

    interop_db.SubmitChanges();

    nwindTxn.Commit();
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine("Error submitting changes... all changes rolled back.");
}

nwindConn.Close();

---------------------------------------------------------------------

IEnumerable<Customer> results = db.ExecuteQuery<Customer>(
    @"select c1.custid as CustomerID, c2.custName as ContactName
        from customer1 as c1, customer2 as c2
        where c1.custid = c2.custid"
);

매개변수 삽입

IEnumerable<Customer> results = db.ExecuteQuery<Customer>( "select contactname from customers where city = {0}", "London" );

 

방법: 데이터베이스에서 행 삭제(LINQ to SQL)

LINQ to SQL에서는 하위 삭제 작업을 지원하거나 인식하지 않습니다. 제약 조건이 있는 테이블의 행을 삭제하려면 다음 작업 중 하나를 수행해야 합니다.

  • 데이터베이스의 외래 키 제약 조건에 ON DELETE CASCADE 규칙을 설정합니다.

  • 사용자 고유의 코드를 사용하여 부모 개체를 삭제하는 데 방해가 되는 자식 개체를 먼저 삭제합니다.

// Query the database for the rows to be deleted.
var deleteOrderDetails =
    from details in db.OrderDetails
    where details.OrderID == 11000
    select details;

foreach (var detail in deleteOrderDetails)
{
    db.OrderDetails.DeleteOnSubmit(detail);
}

try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Provide for exceptions.
}

 

------------------------------------------------------------------------

Northwnd db = new Northwnd(@"c:\northwnd.mdf");

db.Log = Console.Out;

// Specify order to be removed from database
int reqOrder = 10250;

// Fetch OrderDetails for requested order.
var ordDetailQuery =
    from odq in db.OrderDetails
    where odq.OrderID == reqOrder
    select odq;

foreach (var selectedDetail in ordDetailQuery)
{
    Console.WriteLine(selectedDetail.Product.ProductID);
    db.OrderDetails.DeleteOnSubmit(selectedDetail);
}

// Display progress.
Console.WriteLine("detail section finished.");
Console.ReadLine();

// Determine from Detail collection whether parent exists.
if (ordDetailQuery.Any())
{
    Console.WriteLine("The parent is presesnt in the Orders collection.");
    // Fetch Order.
    try
    {
        var ordFetch =
            (from ofetch in db.Orders
             where ofetch.OrderID == reqOrder
             select ofetch).First();
        db.Orders.DeleteOnSubmit(ordFetch);
        Console.WriteLine("{0} OrderID is marked for deletion.", ordFetch.OrderID);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
    }
}
else
{
    Console.WriteLine("There was no parent in the Orders collection.");
}

// Display progress.
Console.WriteLine("Order section finished.");
Console.ReadLine();

try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
    Console.ReadLine();
}

// Display progress.
Console.WriteLine("Submit finished.");
Console.ReadLine();

데이터베이스에 행 삽입(LINQ to SQL)

개체를 연결된 LINQ to SQL Table<(Of <(TEntity>)>) 컬렉션에 추가한 다음 변경 내용을 데이터베이스에 전송하여 행을 데이터베이스에 삽입합니다. LINQ to SQL에서는 변경 내용을 적절한 SQL INSERT 명령으로 변환합니다.

// Create a new Order object.
Order ord = new Order
{
    OrderID = 12000,
    ShipCity = "Seattle",
    OrderDate = DateTime.Now
    // …
};

// Add the new object to the Orders collection.
db.Orders.InsertOnSubmit(ord);

// Submit the change to the database.
try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Make some adjustments.
    // ...
    // Try again.
    db.SubmitChanges();
}

데이터베이스의 행 업데이트(LINQ to SQL)

// Query the database for the row to be updated.
var query =
    from ord in db.Orders
    where ord.OrderID == 11000
    select ord;

// Execute the query, and change the column values
// you want to change.
foreach (Order ord in query)
{
    ord.ShipName = "Mariner";
    ord.ShipVia = 2;
    // Insert any additional changes to column values.
}

// Submit the changes to the database.
try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    Console.WriteLine(e);
    // Provide for exceptions.
}

저장 프로시저를 할당하여 업데이트, 삽입 및 삭제 수행(O/R 디자이너)

저장 프로시저를 지정하여 엔터티 클래스의 기본 동작을 재정의하려면
  1. 디자이너에서 LINQ to SQL 파일을 엽니다. 솔루션 탐색기에서 .dbml 파일을 두 번 클릭합니다.

  2. 서버 탐색기/데이터베이스 탐색기에서 저장 프로시저를 확장하여 엔터티 클래스의 삽입, 업데이트 및/또는 삭제 명령에 사용할 저장 프로시저를 찾습니다.

  3. 저장 프로시저를 O/R 디자이너로 끌어 놓습니다.

    저장 프로시저는 메서드 창에 DataContext 메서드로 추가됩니다. 자세한 내용은 DataContext 메서드(O/R 디자이너)를 참조하십시오.

  4. 업데이트 수행을 위해 저장 프로시저를 사용하려는 엔터티 클래스를 선택합니다.

  5. 속성 창에서 재정의할 삽입, 업데이트 또는 삭제 명령을 선택합니다.

  6. 런타임 사용 옆의 줄임표(...)를 클릭하여 동작 구성 대화 상자를 엽니다.

  7. 사용자 지정을 선택합니다

  8. 사용자 지정 목록에서 원하는 저장 프로시저를 선택합니다.

  9. 메서드 인수 및 클래스 속성 목록을 살펴보고 메서드 인수가 적절한 클래스 속성에 매핑되어 있는지 확인합니다. 업데이트 및 삭제 명령을 위해 원래 메서드 인수(Original_ArgumentName)를 원래 속성(PropertyName (Original))에 매핑합니다.

+ Recent posts