将函数保存到“ System.Data.Entity.Infrastructure.DbUpdateException”上的数据库错误中

时间:2019-04-12 13:04:58

标签: c# visual-studio entity-framework

我的C#应用​​程序使用列表框连接数据库表并更新,删除和创建它们。但是当我想改变关系时。错误。我觉得这与foreach循环中使用的'a'和'w'属性有关。由于他们在使用调试工具时出现此错误:a.id=error CS0103:

  

名称“ a”在当前上下文中不存在

。如果您将答案保持简单,那将是很好的,因为我对C#不太熟悉。

我正在将Windows 10与Microsoft SQL Management Studio一起使用。

public void Save(Company company)
{
    using (WebsiteDBEntities1 db = new WebsiteDBEntities1())
    {
            var dbCompany = db.Companies.Include("Developers").Include("Websites").SingleOrDefault(c => c.id == company.id) ?? new Company();

            dbCompany.name = company.name;
            dbCompany.location = company.location;
            dbCompany.revenue = company.revenue;
            dbCompany.founded_in = company.founded_in;

            //Developers
            dbCompany.Developers.Clear();
            foreach (Developer developer in company.Developers)
            {
                dbCompany.Developers.Add(db.Developers.Single(a => a.id == developer.id));
            }

            //Websites
            dbCompany.Websites.Clear();
            foreach (Website website in company.Websites)
            {
                dbCompany.Websites.Add(db.Websites.Single(w => w.id == website.id));
            }

            db.Companies.AddOrUpdate(dbCompany);
            db.SaveChanges();
    }
}

0 个答案:

没有答案