How create method to delete records in some EF related tables

zleug 51 Reputation points
2020-10-02T20:07:30.23+00:00

Hi All.
In WPF DataGrid I would like to delete a record. The DataGrid is populated by join of two tables Department and EmployeeDept. I create button to delete a record in the DataGrid. But records of source DataGrid are related to other EF related tables
29840-cascadetables.jpg

This diagram displays related tables. For example, if in the EmployeeDept table need to be delete record DepartmentId=7 so in the EmployeeTask table should be deleted all records with related EmployeeDeptId number. If that is possible. How create LINQ or lambda to perform delete method? I will appreciate for detail explanation and sample.

Thanks.

Developer technologies Transact-SQL
SQL Server Other
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Ricardo Mauro 1 Reputation point
    2020-10-04T17:31:16.06+00:00

    Maybe it's better to change in sql.

    You can use cascade delete instead.

    Check out this article https://www.sqlshack.com/delete-cascade-and-update-cascade-in-sql-server-foreign-key/

    0 comments No comments

  2. zleug 51 Reputation points
    2020-10-04T18:28:22.837+00:00

    Hi rmaurodev. Thanks for reply.
    Actualy in project I'm using Entity Framework tables links to SQL Server database. I need to create LINQ or lambda query in method to delete records in multiple tables. If you know how to do it I will appreciate for help.

    Thanks.


  3. Uri Dimant 211 Reputation points
    2020-10-05T09:12:56.853+00:00

    Trigger FOR DELETE ON EmpDep table where you delete the data from the task table ....
    Sorry cannot test it right now

    CREATE TRIGGER sampleTrigger
    ON EmployeeDept
    FOR DELETE
    AS
    DELETE FROM EmployeeTask
    WHERE DepartmentId IN(SELECT deleted.id FROM deleted)

    0 comments No comments

  4. Cris Zhan-MSFT 6,661 Reputation points
    2020-10-05T09:37:03.377+00:00

    Hi,

    Please refer to following posts if help:
    https://stackoverflow.com/questions/29073597/linq-join-to-delete-contents-from-multiple-tables

    https://www.c-sharpcorner.com/UploadFile/scottlysle/cascading-deletes-in-linq-to-sql/


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.