简体   繁体   English

一个字段中有多个值(外键?)

[英]Multiple values in one field (foreign keys?)

在此处输入图片说明 I am trying to do an Ordering System where you can put many Products in one order. 我正在尝试创建一个订购系统,您可以在其中将多个产品放置在一个订单中。 I have very little knowledge about this and this is where i am now 我对此知之甚少,这就是我现在的位置 图片

There are 3 tables, Product table,Order table and the Order-products table. 有3个表,Product表,Order表和Order-products表。 I really don't know if this is right as i am beginner especially on foreign keys. 我真的不知道这是否正确,因为我是初学者,尤其是在外键上。

What I want to achieve is you can order many products and put that products into one "OrderID" like this example in pic below. 我想要实现的是,您可以订购许多产品,并将该产品放入一个“ OrderID”中,如下面的图片中的示例所示。 在此处输入图片说明

This are my only codes. 这是我唯一的代码。 Sorry but i am really lost at this. 抱歉,但是我真的迷失了。

    public Form1()
    {
        InitializeComponent();
        fillCart();
    }


    private void fillCart()
    {
        dgvCart.ColumnCount = 3;
        dgvCart.Columns[0].Name = "ProductID";
        dgvCart.Columns[1].Name = "ProductName";    
        dgvCart.Columns[2].Name = "Quantity";
    }

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        //dgvproducts
    }

    private void Form1_Load(object sender, EventArgs e)
    {
       crud.FillDataGrid("Select * from Products", ref dgvProducts);
       crud.FillDataGrid("Select * from Orders", ref dgvOrder);
       crud.FillDataGrid("Select * from Orderproducts", ref dgvOrderview);
       lbldate.Text = DateTime.Now.ToShortDateString();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        //button add to cart
        addData(dgvProducts.CurrentRow.Cells[0].Value.ToString(), dgvProducts.CurrentRow.Cells[1].Value.ToString(), txtqty.Text);
    }

    private void addData(string p1, string p2, string p3)
    {
        String[] row = { p1, p2, p3 };
        dgvCart.Rows.Add(row);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //button insert

    }

Thank you very much and i hope someone can help me with my problem. 非常感谢您,我希望有人可以帮助我解决我的问题。

Method use for filling datagridview from SQLserver 2008: 从SQLserver 2008填充datagridview的方法使用:

      public crud()
    {
        cnString = "Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=MARISCHELLdatabase;Integrated Security=True";
        cn = new SqlConnection(cnString);
    }



    public void FillDataGrid(string sql, ref ns1.BunifuCustomDataGrid dg)
    {
        try
        {
            DataSet ds = new DataSet();
            cn.Open();
            cmd = new SqlCommand(sql, cn);
            adptr = new SqlDataAdapter(cmd);
            adptr.Fill(ds);
            dg.DataSource = "";
            dg.DataSource = ds.Tables[0];


        }
        catch (Exception e)
        {
            MessageBox.Show("" + e.Message);
        }
        cn.Close();
    }

How Linq 2 SQL dataclasses look for me: Linq 2 SQL数据类如何寻找我: Linq 2 SQL

The code that goes with it: 附带的代码:

//I have 2 columns in my dataGridView, Id 1st amount 2nd
//I added 3 items for testing
List<Tuple<int, int>> cart = new List<Tuple<int,int>>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Cells[0].Value != null && row.Cells[1].Value != null)
    { 
        cart.Add(new Tuple<int, int>(Convert.ToInt32(row.Cells[0].Value.ToString()),Convert.ToInt32(row.Cells[1].Value.ToString())));
                //Now each list item will have .Item1 (productId) and .Item2 (amount)
    }
}
using (DataClasses1DataContext dataContext = new DataClasses1DataContext())
{
    //The tables you add in the dataContext are accessible by name
    Order order = new Order();
    dataContext.Orders.InsertOnSubmit(order);
    dataContext.SubmitChanges(); // Submit once so we get an orderId
    foreach (Tuple<int, int> product in cart)
    {
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.OrderId = order.OrderID;
        orderProduct.ProductId = product.Item1;
        orderProduct.Amount = product.Item2;
        dataContext.OrderProducts.InsertOnSubmit(orderProduct);
    }
    dataContext.SubmitChanges();
}

Create foreign key relationship between Order - OrderProduct over OrderID and Product - OrderProduct over Product ID. 在Order-OrderProduct(通过OrderID)和Product-OrderProduct(通过产品ID)之间创建外键关系。

For each Product in order insert a row into OrderProduct with OrderId 对于订单中的每个产品,在具有OrderId的OrderProduct中插入一行

This may not answer your question completely but consider an object orientated approach to this. 这可能无法完全回答您的问题,但可以考虑采用面向对象的方法。 It's always better in my opinion to have a strongly typed method of accessing values returned from a database, although others may disagree. 在我看来,最好使用一种强类型方法来访问从数据库返回的值,尽管其他人可能会不同意。 Here is some pseudo code to get you started and is by no means the entire solution but should encourage you to think how you can make your code more object orientated and strongly typed. 这里有一些伪代码可以帮助您入门,但这绝不是完整的解决方案,但应鼓励您考虑如何使代码更面向对象和强类型化。 Use the same methodology to save and update tables in your database. 使用相同的方法来保存和更新数据库中的表。

example

    //Business layer
public class Product
{
    public string ProductName {get;set;}
    public int Quantity {get;set;}
    public string Unit {get;set;}
    public decimal Price {get;set;}
    public long Total {get;set;}

    public Product(){}

    public Product(string productName, int quantity, string unit, decimal price, long total)
    {
        ProductName = productName;
        Quantity = quantity;
        Unit = unit;
        Price = price;
        Total = total;
    }

    public List<Product> GetProductList()
    {
        //get the list of products from the data access layer
        ProductDal dal = new ProductDal();
        return dal.GetProductList();
    }
}

//Data layer
public class ProductDal
{
    public List<Product> GetProductList()
    {
        List<Product> lstProducts = new List<Product>();
        //connect to your database code here

        //fill your list with records from your Sql query
        //inside your DataReader while loop you can add a new Product object to your list for each record
        //assuming your database field names match the Product class's proeprties you would do this
        lstProducts.Add(new Product((string)reader["ProductName"],
                                    (int)reader["Quantity"],
                                    (string)reader["Unit"], 
                                    decimal)reader["Price"],
                                    (long)reader["Total"]));

        return lstProducts;
    }
}

//front end code behind page
private void button2_Click(object sender, EventArgs e)
    {
        Product product = new Product();
        dgvCart.DataScource = product.GetProductList();
        dgvCart.DataBind();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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