【发布时间】:2010-02-24 17:50:54
【问题描述】:
我正在学习 LINQ,但无法一次性插入和更新。我有一个 StatusReport 表(School、Customer、Time),其中 School 是主键,还有一个 Service 表(School、ServiceName、State 和 Version),其中 School 是外键,School + ServiceName 是主键.
这是我的更新代码:
public MockReport(int numDrives, int numServers, int numCameras, string customer, string school)
{
_school = school;
string c = "...";
using (DataClasses1DataContext _context = new DataClasses1DataContext(c))
{
_context.CommandTimeout = 60;
Random random = new Random();
bool inserting = false;
_report = _context.StatusReports.SingleOrDefault(s => s.School == school);
if (_report == null)
{
_report = new StatusReport();
inserting = true;
}
updateService("System Monitor", "Running", "1.0.0.0");
_report.Customer = customer;
_report.School = school;
_report.Time = DateTime.Now;
if (inserting)
{
_context.StatusReports.InsertOnSubmit(_report);
}
_context.SubmitChanges();
}
}
private void updateService(string serviceName, string state, string version)
{
Service service = _report.Services.SingleOrDefault(s => s.School == _school && s.ServiceName == serviceName); // returns null!
bool inserting = false;
if(service == null)
{
service = new Service();
inserting = true;
}
service.ServiceName = serviceName;
service.State = state;
service.Version = version;
if(inserting)
{
_report.Services.Add(service);
}
}
插入很好,但更新失败 - 我得到一个 SQL 异常:违反 PRIMARY KEY 约束“PK_dbo.Service”。无法在对象“dbo.Service”中插入重复键。 该语句已终止。
另外,服务 service = _report.Services.SingleOrDefault(s => s.School == _school && s.ServiceName == serviceName);即使数据存在,也返回 null。
有什么想法吗?
【问题讨论】:
标签: linq-to-sql insert parent-child