Best way to delete a record using LINQ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Big Daddy

    #1

    Best way to delete a record using LINQ?

    I am trying to do all my DB access through LINQ. For example, I am
    trying to delete a record from the JobQueue table. There’s a couple
    ways I could do this:

    1. Method 1 – The disadvantage is that it makes 2 calls to the DB: one
    to get the record and then one to delete it:

    using (LogicDataConte xt ctx = new LogicDataContex t(m_strConnect) )
    {
    JobQueue jq = ctx.JobQueues.S ingle(queue =queue.JobQueue No ==
    queueNo);
    ctx.JobQueues.D eleteOnSubmit(j q);
    ctx.SubmitChang es();
    }

    2. Method 2 – The disadvantage is that I’m writing SQL directly, which
    I don’t want to do. In fact, it’s the whole reason I’m using LINQ.

    using (LogicDataConte xt ctx = new LogicDataContex t(m_strConnect) )
    {
    string str = "Delete JobQueue WHERE JobQueueNo = " + queueNo;
    ctx.ExecuteComm and(str);
    }

    3. Method 3 – This doesn't work because it throws an exception: "Row
    not found or changed." It doesn't make two trips to the DB like
    method 1, but instead tries to attach a JobQueue to the data context.
    But will only work if all the column values are exactly the same as
    the values in the DB:

    using (LogicDataConte xt ctx = new LogicDataContex t(m_strConnect) )
    {
    JobQueue jq = new JobQueue() { JobQueueNo = requestQueueNo };
    ctx.JobQueues.A ttach(jq, false);
    ctx.JobQueues.D eleteOnSubmit(j q);
    ctx.SubmitChang es();
    }

    Is there a better way? I think LINQ should have a built in function
    to delete a record using the primary key.

    I guess if I was going to use the second method, I could write a
    helper function that would use reflection to create the DELETE
    statement using the table name and the fact that the primary key
    column property has an attribute on it like this:

    [Column(Storage= "_JobQueueN o", AutoSync=AutoSy nc.OnInsert,
    DbType="Int NOT NULL IDENTITY", IsPrimaryKey=tr ue,
    IsDbGenerated=t rue)]

    Thanks in advance,
    John
Working...