Foreign key conflict detection before deleting data in. Net

Source: Internet
Author: User

In writing a database system, the easiest and safest way to ensure data consistency in the system is to establish a foreign key constraint in the DBMS. However, if the foreign key constraint is violated when deleting the primary key data, although the DBMS will give an error message, for example, the prompt message "% 1! Statement and % 2! % 3! Constraint '% 4! 'Conflicted. This conflict occurred in database '% 6! ', Table' % 8! '% 10! % 11! % 13 !.", However, these prompts are unfriendly to end users, so they write a class to detect foreign key conflicts when deleting records. The Code is as follows:
Using System;
Using System. Data;
Using System. Data. SqlClient;
Using Microsoft. ApplicationBlocks. Data;
Namespace DataAccess. SQLServerDAL
{
///
/// Summary of Check.
///
Public class Check
{
///
/// DBMS
///
Const string DEFAULT_SYSTABLES = "systables ";
# Region CkeckFKBeginDelete
///
/// Check whether a foreign key conflict exists before deleting the record.
///
/// Object
/// Name of the table to be deleted
/// Primary key value of the record to be deleted
/// Error message returned
/// True-no conflict, false-conflict exists
Public bool CkeckFKBeginDelete (SqlTransaction trans, string tableName, string id, ref string errText)
{
String selectString; // SQL query statement
String fkTableName; // Foreign key table name
String fkColumnName; // Foreign key column name
Object obj; // the return value of the SQL query.
String description; // meaning of the foreign key table
Int count; // number of records that reference the primary key in the foreign key table
String [] tableNames = {"sysforeignkeys "};
DataSet ds = BuildDataTables ();
// Retrieve all the foreign key tables of this table
SelectString = "SELECT fkeyid, fkey FROM sysforeignkeys a, sysobjects B WHERE a. rkeyid = B. id AND B. name = @ name ";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.