LINQ to SQL : Delete data through Object Model

LINQ to SQL support deleting data through object. Continuing with my previous blog on INSERT, let me discuss about the delete method

static void Main(string[] args)

{

    string strConnection = @"Connection String";

    TestDB db = new TestDB(strConnection);

    db.Log = Console.Out;

       

    //Here I am finding the employee with Id 18

    //You can get an error if id does not exists

    var deleteQ = db.Emps.First(e => e.Id == 18);

   

    //Delete the specific entry from collection

    db.Emps.Remove(deleteQ);

    //Commit the changes to database

    //at this point DML gets generated

  db.SubmitChanges();

   

}

Now the line db.Log = Console.Out; gives me the SQL query generated by the background engine.

DELETE FROM [Emp] WHERE ([Name] = @p0) AND ([Id] = @p1)

SELECT

    (CASE

        WHEN (@@ROWCOUNT) > 0 THEN @@ROWCOUNT

        ELSE (

            SELECT -1

            WHERE NOT (EXISTS(

                SELECT NULL AS [EMPTY]

                FROM [Emp] AS [t1]

                WHERE [t1].[Id] = @p2

                ))

            )

     END) AS [value]

-- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) NOT NULL [Writam]

-- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) NOT NULL [18]

-- @p2: Input Int (Size = 0; Prec = 0; Scale = 0) NOT NULL [18]

SqlProvider\AttributedMetaModel

All the methods are coming from DataContext class (responsible for SQL query generation). The above method converts the object addition to DML query.

Namoskar!!!