Wriju's BLOG

.NET, Cloud and everything

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



    //Commit the changes to database

    //at this point DML gets generated





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)




        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]




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