Как правильно назначить первичный ключ для DataTable в C #? - PullRequest
1 голос
/ 16 апреля 2019

У меня есть DataTable, в котором указаны названия должностей.Я пытаюсь установить столбец JobTitle в качестве первичного ключа, но не могу заставить его работать.Где я ошибаюсь?

Я использовал как код из StackOverflow, так и сайт Microsoft безрезультатно.

public class AutoEnrolTable
{
    public DataTable autoEnrolDT { get; private set; }
    private Dictionary<int, string> dictJobTitles;
    private Dictionary<int, string> dictAssessments;

    public AutoEnrolTable()
    {
        autoEnrolDT = new DataTable();
        dictAssessments = new Dictionary<int, string>();
        dictJobTitles = new Dictionary<int, string>();
        autoEnrolDT.Columns.Add("Job Title", typeof (string));
        SetAssessmentsDict();
        SetJobTitlesDict();
        SetAssessments();
        SetJobTitles();
        autoEnrolDT.PrimaryKey = new DataColumn[] { autoEnrolDT.Columns["Job Title"] };
    }

    private void SetAssessmentsDict()
    {
        SqlStoredProcedure sp = new SqlStoredProcedure("GetAssessmentAndModule", DB.conStr);

        DataTable dt = sp.ExecuteAndReturnDataTable();

        foreach (DataRow assessment in dt.Rows)
        {
            int assessmentID = assessment.Field<int>("AssessmentID");
            string assessmentName = assessment.Field<string>("AssessmentName");
            dictAssessments.Add(assessmentID, assessmentName);
        }
    }

    private void SetJobTitlesDict()
    {
        SqlStoredProcedure sp = new SqlStoredProcedure("GetJobTitleAndDepartment", DB.conStr);

        DataTable dt = sp.ExecuteAndReturnDataTable();

        foreach (DataRow jobTitle in dt.Rows)
        {
            int adJobTitleID = jobTitle.Field<int>("AD_JobTitleID");
            string jobTitleName = jobTitle.Field<string>("JobTitleAndDepartment");
            dictJobTitles.Add(adJobTitleID, jobTitleName);
        }
    }

    private void SetAssessments()
    {
        foreach (KeyValuePair<int, string> entry in dictAssessments)
        {
            autoEnrolDT.Columns.Add(entry.Value);
        }            
    }

    private void SetJobTitles()
    {
        foreach (KeyValuePair<int, string> entry in dictJobTitles)
        {
            DataRow dataRow = autoEnrolDT.NewRow();
            dataRow["Job Title"] = entry.Value;
            autoEnrolDT.Rows.Add(dataRow);
        }
    }
}
...