从我的代码中可以看出,我绝对是初学者。在查找LINQ to SQL问题的其他类似问题后,我发现自己似乎仍然坚持两个目标。 1)使用来自三个组合框和日期选择器的用户选择的输入添加新条目,以及2)使用来自datagridview的交互更新现有数据库条目。
我的windows表格datagridview显示以下输出
**select b.Date, a.EmployeeName,
c.ProjectName, b.Hours
from dbo.Employees a
left outer join dbo.EmployeeProjectHours b
on a.EmployeeId = b.EmployeeId
left outer join dbo.Projects c
on b.ProjectId = c.ProjectId**
这是我的ADD方法,用户向我提供了ProjectName,EmployeeName,Date和Hours。对外行人的任何想法都会受到赞赏。
运行插入时没有出错,但是我的dab也没有添加任何内容
using (ProjectHoursDataContext dbInsert = new ProjectHoursDataContext())
{
this.Validate();
EmployeeProjectHour empHours = new EmployeeProjectHour();
empHours.Date = dateDateTimePicker.Value;
empHours.Hours = Convert.ToDecimal(hoursComboBox.Text);
empHours.ProjectId = dbInsert.Projects.First(p => p.ProjectName == projectNameComboBox.Text).ProjectId;
empHours.EmployeeId = dbInsert.Employees.First(m => m.EmployeeName == employeeNameComboBox.Text).EmployeeId;
db.EmployeeProjectHours.InsertOnSubmit(empHours);
dbInsert.SubmitChanges();
}
这是我的更新尝试直接从datagridview使用更新。我收到以下错误: System.Windows.Forms.dll中出现'System.ArgumentException'类型的第一次机会异常
using (ProjectHoursDataContext dbUpdate = new ProjectHoursDataContext())
{
this.Validate();
dataGridView1.AutoGenerateColumns = true;
projectBindingSource.DataSource = dbUpdate;
projectBindingSource.DataMember = "Updates";
projectBindingSource.EndEdit();
dbUpdate.SubmitChanges();
}
答案 0 :(得分:0)
我最好的猜测到目前为止,您想要修改和更改现有的Employee
,Project
和EmployeeProjectHours
记录。
所以你会这样做:
using (ProjectHoursDataContext dbInsert = new ProjectHoursDataContext())
{
this.Validate();
// Get the records
Employee emp = new Employee();
Project proj = new Project();
EmployeeProjectHour empHours = new EmployeeProjectHour();
// Set new values to Employees tables
emp = dbInsert.Employees
.First(m => m.EmployeeName == employeeNameComboBox.Text);
//just get the empployee
//setting values will update it
emp.EmployeeName = employeeNameComboBox.Text;
// GET an existing project
proj = dbInsert.Projects
.First(p => p.ProjectName == projectNameComboBox.Text);
//update its values.
proj.ProjectName = projectNameComboBox.Text;
proj.ProjectDescription = "Test";
//GET an empHours
empHours = dbInsert.Projects.First(p => p.EmployeeId == emp.EmployeeId &&
p.ProjectId == proj.ProjectId);
//set its values
empHours.Date = dateDateTimePicker.Value;
empHours.Hours = Convert.ToDecimal(hoursComboBox.Text);
dbInsert.SubmitChanges();
}
答案 1 :(得分:0)
除了下面的新代码,我还将项目数据库的增量状态设置为NO。我从之前的stackoverflow讨论中得到了肯定。感谢
public void AddInfo()
{
db.Connection.Open();
this.Validate();
EmployeeProjectHour empHours = new EmployeeProjectHour();
empHours.Date = dateDateTimePicker.Value;
empHours.Hours = Convert.ToDecimal(hoursComboBox.Text);
empHours.ProjectId = db.Projects.First(p => p.ProjectName == projectNameComboBox.Text).ProjectId;
empHours.EmployeeId = db.Employees.First(m => m.EmployeeName == employeeNameComboBox.Text).EmployeeId;
db.EmployeeProjectHours.InsertOnSubmit(empHours);
db.SubmitChanges();
db.Connection.Close();
}