Tuesday, May 8, 2012

http://www.roque-patrick.com/windows/final/bbl0201.html

DataSet ds = new DataSet();
SqlConnection cn = new SqlConnection(
ConfigurationSettings.AppSettings("ConnectString"));SqlCommand cmd = new SqlCommand("usp_FillTransactions", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter daTransactions = new SqlDataAdapter(cmd);
daTransactions.Fill(ds, "Transactions");  

//pass in ds as DataSet, and "Transactions" as the table name
SqlCommand cmdDetails = new SqlCommand("usp_FillTransactionDetails", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter daTransactionDetails = new SqlDataAdapter(cmdDetails);
daTransactionDetails.Fill(ds, "Details");



DataRelation Tran_Detail =
new DataRelation("ds", ds.Tables[0].Columns["TransID"], ds.Tables[1].Columns["TransID"]);
//For the sake of brevity I'm not going to translate each of the above, but you can switch between the nominal or the ordinal and provided
//you use the correct index, it will work the same
ds.Relations.Add(Tran_Detail);

Like I said, this is the simplest of the constructors. The other overloads are provided below:

DataRelation(string, ParentDataColum(), ChildDataColumn())  

'this takes an array of DataColumns, so you could use this constructor the same way we did above

DataRelation(string, ParentDataColumn, ChildDataColumn, Boolean)

//Where the boolean instructs the DataRelation whether or not to enforce the constraints.  For good reason Constraints are enabled by default, and I'd recommend against setting this to false unless you have a really good reason to do so...and if you do, don't complain to me when a user does something you didn't intend and your validation code misses it.Similarly, there is an Array Based constructor with the Boolean:

DataRelations(string, ParentDataColumn(), ChildDataColumn(), Boolean)
//this is identical to the one above it except it allows the use of multiple columns aka Composite Keys
The final constructor allows you to simply name the tables and the columns, but this will already be done most of the time.  For that reason, I'm not going to address, but it's Here if you find the need to use it.

 
DataColumn[] TransactionColumns;
DataColumn[] DetailColumns;

TransactionColumns = new DataColumn[] {ds.Tables[0].Columns["TransID"], ds.Table[0].Columns["CustomerID"], ds.Tables[0].Columns["SalePersonID"]};
DetailColumns = new DataColumn[] {ds.Tables[1].Columns["TransID"], ds.Table[1].Columns["CustomerID"], ds.Tables[1].Columns["SalePersonID"]};

DataRelation Tran_Detail = new DataRelation("myDataRelation", TransactionColumns, DetailColumns);
ds.Relations.Add(Tran_Detail);




*********
{
    // Create a Projects list    ProjectList projects = new ProjectList();

    // Set SQL query to fetch projects    string sqlQuery =
      "Select * from Projects; Select * from Steps";

    // Create dataset    DataSet dataSet = new DataSet();

    // Populate dataset    using (SqlConnection connection =
           new SqlConnection(m_ConnectionString))
    {
        SqlCommand command = new SqlCommand(sqlQuery, connection); SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
        dataAdapter.Fill(dataSet);
    }

    // Set dataset table names    dataSet.Tables[0].TableName = "Projects";
    dataSet.Tables[1].TableName = "Steps";

    // Create a data relation between projects    // (parents) and steps (children)    DataColumn parentColumn =
       dataSet.Tables["Projects"].Columns["ProjectID"];
    DataColumn childColumn =
       dataSet.Tables["Steps"].Columns["ProjectID"];
    DataRelation projectsToSteps =
       new DataRelation("ProjectsToSteps",
       parentColumn, childColumn);
    dataSet.Relations.Add(projectsToSteps);

    // Create a Projects collection from the data set    ProjectList projectList = new ProjectList();
    ProjectItem nextProject = null;
    StepItem nextStep = null;
    foreach (DataRow parentRow in dataSet.Tables["Projects"].Rows)
    {
        // Create new project         nextProject = new ProjectItem();

        // Fill in its properties        nextProject.ID = Convert.ToInt32(parentRow["ProjectID"]);
        nextProject.Name = parentRow["Name"].ToString();

        /* Read in other fields from the record... */

        // Get its steps        DataRow[] childRows =
          parentRow.GetChildRows(dataSet.Relations["ProjectsToSteps"]);

        // Create StepItem objects for each of its steps        foreach (DataRow childRow in childRows)
        {
            // Create new step            nextStep = new StepItem();

            // Fill in its properties            nextStep.ID = Convert.ToInt32(childRow["StepID"]);
            nextStep.Date = Convert.ToDateTime(childRow["Date"]);
            nextStep.Description = childRow["Description"].ToString();

            // Add new step to the project            nextProject.Steps.Add(nextStep);
        }

        // Add new project to the Projects list        projectList.Add(nextProject);
    }

    // Dispose of the DataSet    dataSet.Dispose();

    // Set return value    return projectList;
}


****
parent and child table relation
public void LoadAuthorList(AuthorList authorList)
{
    // Build query to get authors and their books    StringBuilder sqlQuery = new StringBuilder();
    sqlQuery.Append("Select AuthorID, LastName," +
                    " FirstName, SSNumber From Authors; ");
    sqlQuery.Append("Select BookID, SkuNumber," +
                    " AuthorID, Title, Price From Books");

    // Get a data set from the query    DataSet dataSet =
      DataProvider.GetDataSet(sqlQuery.ToString());

    // Create variables for data set tables    DataTable authorsTable = dataSet.Tables[0];
    DataTable booksTable = dataSet.Tables[1];

    // Create a data relation from Authors    // (parent table) to Books (child table)    DataColumn parentColumn = authorsTable.Columns["AuthorID"];
    DataColumn childColumn = booksTable.Columns["AuthorID"];
    DataRelation authorsToBooks = new
      DataRelation("AuthorsToBooks", parentColumn, childColumn);
    dataSet.Relations.Add(authorsToBooks);

    // Load our AuthorList from the data set    AuthorItem nextAuthor = null;
    BookItem nextBook = null;
    foreach (DataRow parentRow in authorsTable.Rows)
    {
        // Create a new author        bool dontCreateDatabaseRecord = false;
        nextAuthor = new AuthorItem(dontCreateDatabaseRecord);

        // Fill in author properties        nextAuthor.ID = Convert.ToInt32(parentRow["AuthorID"]);
        nextAuthor.FirstName = parentRow["FirstName"].ToString();
        nextAuthor.LastName = parentRow["LastName"].ToString();
        nextAuthor.LastName = parentRow["LastName"].ToString();
        nextAuthor.SSNumber = parentRow["SSNumber"].ToString();

        // Get author's books        DataRow[] childRows = parentRow.GetChildRows(authorsToBooks);

        // Create BookItem object for each of the authors books        foreach (DataRow childRow in childRows)
        {
            // Create a new book            nextBook = new BookItem();

            // Fill in book's properties            nextBook.ID = Convert.ToInt32(childRow["BookID"]);
            nextBook.SkuNumber = childRow["SkuNumber"].ToString();
            nextBook.Title = childRow["Title"].ToString();
            nextBook.Price = Convert.ToDecimal(childRow["Price"]);

            // Add the book to the author            nextAuthor.Books.Add(nextBook);
        }

        // Add the author to the author list        authorList.Add(nextAuthor);
    }

    // Dispose of the data set    dataSet.Dispose();
}

No comments:

Post a Comment