简体   繁体   中英

Linq to sql deleteAllOnSubmit referential integrity

Let's say I have the following classes that:

    Module
    {
        long MID    // PK
        string Name
    }

    ModuleBlock
    {
        long MID      // FK
        long BID      // FK
    }

    Block
    {
        long BID      // PK
        string Info
    }

    BlockLanguage
    {
        long BID      // FK
        long LID      // FK
    }

    Language
    {
        long LID      // FK
        string Language
    }

Imagine these are filled with data. Now, I'd like to delete a set of Blocks. How do I have to do this? I have to delete the appropriate ModuleBlocks and BlockLanguages.

let's say this is the list of Block I'd like to delete:

    var blocks = // blocks query here

I probably have to call:

    Context.Blocks.DeleteAllOnSubmit(blocks);

But what else do I have to call to make sure the data is deleted in ModuleBlock & BlockLanguage as well?

You can probably use the associated objects to do this.

Context.ModuleBlocks.DeleteAllOnSubmit(blocks.ModuleBlocks);
Context.BlockLanguages.DeleteAllOnSubmit(blocks.BlockLanguages);
Context.Blocks.DeleteAllOnSubmit(blocks);

Yes you need to delete child objects manually. There is one trick though: Set the foreign keys to CASCADE in SQL Server. It will then auto-delete associated objects. This is the fastest and easiest solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM