使用Linq-to-SQL +子关系更新/插入时出现问题

时间:2010-02-24 17:50:54

标签: linq-to-sql insert parent-child

我正在学习LINQ,并且无法一次性插入和更新。我有一个StatusReport表(学校,客户,时间),其中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'中插入重复键。 声明已经终止。

此外,服务服务= _report.Services.SingleOrDefault(s => s.School == _school&& s.ServiceName == serviceName);即使数据存在,也返回null。

有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

您的主键约束错误告诉您,您尝试插入新值的表格中某处存在重复值。因此,您的新值将与已存在的值重复。

检查情况并非如此。

关于第二个错误:如果Service是一个对象,我不知道你的SingleOrDefault方法会为你创建那个对象......

您应该创建Service对象,然后在数据库中找到要更新的数据,将其粘贴到Service对象中,更新对象并提交到数据库。