Tom Gullen
Tom Gullen

Reputation: 61727

c# Linq - Is this a good design for deleting records?

/// <summary>
/// Deletes a template data record
/// </summary>
/// <param name="RecordID">ID of the record</param>
public static void DeleteDataRecord(int RecordID)
{
    ArtworkingDataContext dc = new ArtworkingDataContext();

    // Delete associated datalabels
    var q = dc.tblArtworkDataLabels.Where(c => c.dataID == RecordID);
    dc.tblArtworkDataLabels.DeleteAllOnSubmit(q);
    dc.SubmitChanges();

    // Delete the data record        
    var qq = dc.tblArtworkDatas.Where(c => c.ID == RecordID);
    dc.tblArtworkDatas.DeleteAllOnSubmit(qq);
    dc.SubmitChanges();
}

Do I need to invoke deleteallonsubmit() twice, or can I have it just the once?

Upvotes: 1

Views: 140

Answers (4)

smartcaveman
smartcaveman

Reputation: 42246

No, Deleting Is Bad Design

Upvotes: 0

taylonr
taylonr

Reputation: 10790

q and qq are not the same type of objects, so you'd have to call it twice, I believe.

You don't have to call dc.SubmitChanges() twice.

Additionally, you could set up your DB so that ArtworkData and ArtworkDataLabels are related with a cascading delete. Then you could delete the primary and the secondary would be deleted as well.

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160902

A better approach would be to have a FK relationship between ArtworkDatas and ArtworkDataLabel with a cascading delete set up in the DB - in that case you would not have to delete tblArtworkDataLabels at all, it would happen automatically.

Upvotes: 5

asawyer
asawyer

Reputation: 17808

YOu need two DeleteAllOnSubmit(...) calls, but only one Context.SubmitChanges().

I also suggest wrapping your context in a Using(...) clause.

public static void DeleteDataRecord(int RecordID)
{
    using(var dc = new ArtworkingDataContext())
    {
        // Delete associated datalabels
        var q = dc.tblArtworkDataLabels.Where(c => c.dataID == RecordID);
        dc.tblArtworkDataLabels.DeleteAllOnSubmit(q);
        dc.SubmitChanges();

        // Delete the data record        
        var qq = dc.tblArtworkDatas.Where(c => c.ID == RecordID);
        dc.tblArtworkDatas.DeleteAllOnSubmit(qq);
        dc.SubmitChanges();
    }
}

Upvotes: 1

Related Questions