将外键引用的所有数据导出到数据网格

时间:2019-07-01 12:00:31

标签: c# sql winforms entity-framework

我创建了一个用于用户操作(添加,更新和删除)及其活动的小型应用程序。我有一个包含2个表的数据库:第一个用户和第二个活动。该关系是一对多的,在第二个表中有一个外键,即第一个表中的User_ID。在前端,我有一个带有数据网格的表单,其中包含用户表中的所有成员。双击其中一个时,将打开第二个框,其中包含该用户的所有活动。 为了检索该人的活动,我执行以下操作:

void updateActions()
        {
            using (I2SEntities1 db = new I2SEntities1())
                dgActions.DataSource = db.Actions.Where(x => x.Client_ID.Equals(Main.client.Client_ID)).ToList<Action>();

        }

这行得通,但看起来效率不高,因为每次我都要遍历所有表时。我看到生成的代码中的实体框架生成了ICollection<Activities>。有什么方法可以利用它,并使我的应用程序更高效。

我的意思是做这样的事情。

void updateActions()
        {
            using (I2SEntities1 db = new I2SEntities1())
                //dgActions.DataSource = db.Actions.Where(x => x.Client_ID.Equals(Main.client.Client_ID)).ToList<Action>();
                dgActions.DataSource = Main.client.Actions.ToList<Action>();
        }

这是以下错误

System.ObjectDisposedException: 'The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.'

这是孔代码。

 namespace I2S
    {
        public partial class Main : Form
        {
           public static Client client = new  Client();


            public Main()
            {
                InitializeComponent();

            }


            private void btnCancel_Click(object sender, EventArgs e)
            {
                Clear();
            }
            void Clear()
            {
                txtName.Text = txtPhone.Text = txtAddress.Text = "";
                btnAdd.Text = "Add";
                btnDelete.Enabled = false;
                client.Client_ID = 0;
            }

            private void btnDelete_Click(object sender, EventArgs e)
            {
                if(MessageBox.Show("Do you really want to delete this user ?" , "Delete User" , MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    using (I2SEntities1 db = new I2SEntities1())
                    {
                        var entry = db.Entry(client);
                        if (entry.State == System.Data.Entity.EntityState.Detached)
                            db.Clients.Attach(client);
                        db.Clients.Remove(client);

                        db.SaveChanges();
                        MessageBox.Show("Deleted Successfully");

                    }
                    Clear();
                    update_Grid();


                }
            }

            private void btnAdd_Click(object sender, EventArgs e)
            {
                client.Name = txtName.Text.Trim();
                client.Address = txtAddress.Text.Trim();
                client.Telephone = txtPhone.Text.Trim();

                using (I2SEntities1 db = new I2SEntities1())
                {
                    if (client.Client_ID == 0)
                    {
                        db.Clients.Add(client);
                        db.SaveChanges();


                        MessageBox.Show("New user added");
                    }
                    else
                    {
                        db.Entry(client).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();



                        MessageBox.Show("User Updated Successfully");
                    }
                    Clear();
                    update_Grid();

                }


            }

            private void Main_Load(object sender, EventArgs e)
            {
                update_Grid();

            }


            void update_Grid()
            {
                dgClients.AutoGenerateColumns = false;
                using (I2SEntities1 db = new I2SEntities1())
                {
                    dgClients.DataSource = db.Clients.ToList<Client>();


                }
            }
            private void dgClients_CellClick(object sender, DataGridViewCellEventArgs e)
            {

                if (dgClients.CurrentRow.Index != -1)
                {
                    client.Client_ID = Convert.ToInt32(dgClients.CurrentRow.Cells["Client_ID"].Value);
                }
                using (I2SEntities1 db = new I2SEntities1())
                {
                    client = db.Clients.Where(x => x.Client_ID == client.Client_ID).FirstOrDefault();
                    txtName.Text = client.Name;
                    txtAddress.Text = client.Address;
                    txtPhone.Text = client.Telephone;

                }
                btnAdd.Text = "Update";
                btnDelete.Enabled = true;

            }
            private void dgClients_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
            {
                if (dgClients.CurrentRow.Index != -1)
                {
                    client.Client_ID = Convert.ToInt32(dgClients.CurrentRow.Cells["Client_ID"].Value);
                }
                Form2 actionsForm = new Form2();



                actionsForm.Show();
            }




        }
    }


    namespace I2S
    {
        public partial class Form2 : Form
        {
            Action action = new Action();

            public Form2()
            {
                InitializeComponent();
            }

            private void Form2_Load(object sender, EventArgs e)
            {
                Clear();
                txtDateStart.Format = DateTimePickerFormat.Short;
                txtTimeStart.Format = DateTimePickerFormat.Time;
                txtDateEnd.Format = DateTimePickerFormat.Short;
                txtTimeEnd.Format = DateTimePickerFormat.Time;


                btDeleteAction.Enabled = false;
                updateActions();
            }

            private void dgActions_CellClick(object sender, DataGridViewCellEventArgs e)
            {
                if(dgActions.CurrentRow.Index != -1)
                {
                    action.Action_Id = Convert.ToInt32(dgActions.CurrentRow.Cells["Action_ID"].Value);
                }
                using (I2SEntities1 db = new I2SEntities1())
                {
                    action = db.Actions.Where(x => x.Action_Id == action.Action_Id).FirstOrDefault();
                    txtActionDescription.Text = action.Action_Desc;
                    txtDateStart.Text = action.Action_Beggin.Date.ToString();
                    txtTimeStart.Text = action.Action_Beggin.TimeOfDay.ToString();
                    txtDateEnd.Text = action.Action_End.Date.ToString();
                    txtTimeEnd.Text = action.Action_End.TimeOfDay.ToString();
                }
                btAddAction.Text = "Update";
                btDeleteAction.Enabled = true;

            }

            private void btDeleteAction_Click(object sender, EventArgs e)
            {
                if (MessageBox.Show("Do you really want to delete this action ?", "Delete Action", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    using (I2SEntities1 db = new I2SEntities1())
                    {
                        var entry = db.Entry(action);
                        if (entry.State == System.Data.Entity.EntityState.Detached)
                            db.Actions.Attach(action);
                        db.Actions.Remove(action);
                        MessageBox.Show("Action Sucesfully Removed");

                        db.SaveChanges();

                    }
                    Clear();
                    updateActions();
                }
            }

            private void btAddAction_Click(object sender, EventArgs e)
            {
                action.Action_Desc = txtActionDescription.Text.Trim();

                action.Action_Beggin = Convert.ToDateTime(txtDateStart.Value.Date + txtTimeStart.Value.TimeOfDay);
                action.Action_End = Convert.ToDateTime(txtDateEnd.Value.Date + txtTimeEnd.Value.TimeOfDay);
                action.Client_ID = Main.client.Client_ID;

                using (I2SEntities1 db = new I2SEntities1())
                {
                    if (action.Action_Id == 0)
                    {
                        db.Actions.Add(action);
                        db.SaveChanges();

                        MessageBox.Show("New action added");
                    }
                    else
                    {
                        db.Entry(action).State = System.Data.Entity.EntityState.Modified;


                        db.SaveChanges();

                        MessageBox.Show("Action Succesfully Updated");
                    }
                }
                Clear();
                updateActions();

            }
            void updateActions()
            {
                using (I2SEntities1 db = new I2SEntities1())
                    dgActions.DataSource = db.Actions.Where(x => x.Client_ID.Equals(Main.client.Client_ID)).ToList<Action>();
            }



            private void btClear_Click(object sender, EventArgs e)
            {
                Clear();
            }
            void Clear()
            {
                txtActionDescription.Text = txtDateStart.Text =  txtTimeStart.Text = txtDateEnd.Text = txtTimeEnd.Text= "";
                btDeleteAction.Enabled = false;
                btAddAction.Text = "Add";
                action.Action_Id = 0;
            }
        }
    }

 The DTO's for `Client` and `Actions` :

        namespace I2S
    {
        using System;
        using System.Collections.Generic;

        public partial class Client
        {
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
            public Client()
            {
                this.Actions = new HashSet<Action>();
            }

            public int Client_ID { get; set; }
            public string Name { get; set; }
            public string Address { get; set; }
            public string Telephone { get; set; }

            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
            public virtual ICollection<Action> Actions { get; set; }
        }
    }


    namespace I2S
    {
        using System;
        using System.Collections.Generic;

        public partial class Action
        {
            public int Action_Id { get; set; }
            public string Action_Desc { get; set; }
            public System.DateTime Action_Beggin { get; set; }
            public System.DateTime Action_End { get; set; }
            public int Client_ID { get; set; }

            public virtual Client Client { get; set; }
        }
    }

    namespace I2S
    {
        using System;
        using System.Data.Entity;
        using System.Data.Entity.Infrastructure;

        public partial class I2SEntities1 : DbContext
        {
            public I2SEntities1()
                : base("name=I2SEntities1")
            {
            }

            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                throw new UnintentionalCodeFirstException();
            }

            public virtual DbSet<Action> Actions { get; set; }
            public virtual DbSet<Client> Clients { get; set; }
        }
    }

0 个答案:

没有答案