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

Linq to sql 使用Linq更新/插入SQL时出现问题+;子女关系,linq-to-sql,insert,parent-child,Linq To Sql,Insert,Parent Child,我正在学习LINQ,在一次性插入和更新时遇到困难。我有一个StatusReport表(School、Customer、Time),其中School是主键,还有一个Service表(School、ServiceName、State和Version),其中School是外键,School+ServiceName是主键 这是我的更新代码: public MockReport(int numDrives, int numServers, int numCameras, string customer,

我正在学习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异常:违反主键约束“PK_dbo.Service”。无法在对象“dbo.Service”中插入重复的密钥。 声明已终止

另外,Service Service=\u report.Services.SingleOrDefault(s=>s.School=\u School&&s.ServiceName==ServiceName);返回null,即使数据存在


有什么想法吗?

您的主键约束错误告诉您,在您试图插入新值的表中某处存在重复值。因此,新值将是现有值的副本

检查一下,情况并非如此

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


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

我认为SingleOrDefault()将检索数据库中的对象。然后我更改该对象,并调用SubmitChanges()将更改提交给该对象。SingleOrDefault将从集合中获取一项,如果集合为null,则返回null。SingleOrDefault始终对null集合引发异常。当Func返回true时,重载SingleOrDefault(Func)将从集合中检索单个项;当未找到此类项时,重载SingleOrDefault(Func)将从集合中检索null。