开发者

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

/// <summary>
/// Deletes a template data record
/// </summary>
/// &l开发者_运维问答t;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?


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.


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();
    }
}


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.


No, Deleting Is Bad Design

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜