我的数据库中有以下课程:
public class Medication
{
public int Id { get; set; }
public string Name { get; set; }
}
在我的表单上,我有一个名为Medications
的CheckListBox,要填充该框,我执行了以下操作:
using (DatabaseContext db = new DatabaseContext())
{
medicationBindingSource.DataSource = db.Medications.ToList();
Medications.DataSource = medicationBindingSource;
Medications.DisplayMember = "Name";
Medications.ValueMember = "Id";
}
这很好,但是我面临的一个问题是,当我检查任何项目时,列表中的项目都更改为ID,另一个问题是我无法保存为特定客户检查了哪些项目,数据库中的客户看起来像:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Medication> Medications { get; set; }
这是我用来保存ID和名称的代码:
private void btnSave_Click(object sender, EventArgs e)
{
using (DatabaseContext db = new DatabaseContext())
{
Customer obj = customerBindingSource.Current as Customer;
if (obj != null)
{
if (db.Entry<Customer>(obj).State == System.Data.Entity.EntityState.Detached)
db.Set<Customer>().Attach(obj);
if (obj.Id == 0)
db.Entry<Customer>(obj).State = System.Data.Entity.EntityState.Added;
else
db.Entry<Customer>(obj).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
customerBindingSource.DataSource = db.Customers.ToList();
}
}
}
我的问题是:如何防止CheckListBox将文本更改为Id,如何为每个客户保存CheckListBox?