Я создал небольшое приложение для манипулирования пользователями (добавления, обновления и удаления) и для их действий.У меня есть база данных с 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; }
}
}