我显然是通过在数据库中创建表的类来使用LINQ插入数据,但是它只是显示对象为null的错误。
这是我使用C#LINQ的示例代码:
using (dc = new linqDBDataContext(conn))
{
Subject_Curriculum sc;
Subject_Schedule ss;
Subject_Department sd;
Subject_Standing sst;
Pre_Requisite pr;
Pre_Requisite_Year_Standing prys;
Curriculum cu = new Curriculum();
cu.Curriculum_Title = curriculumName;
cu.Course_Number = courseNumber;
foreach (var s in ssd)
{
sc = new Subject_Curriculum();
sc.Course_Code = s.courseCode;
sc.Course_Title = s.courseTitle;
cu.Subject_Curriculums.Add(sc);
dc.Subject_Curriculums.InsertOnSubmit(sc);
for (int i = 0; i < s.numberOfSchedules; i++)
{
ss = new Subject_Schedule();
if (i == 0)
{
ss.Units = s.unitsLec;
ss.Schedule_Type = "Lecture";
ss.Number_Of_Hours = s.numberOfHoursLec;
}
else
{
ss.Units = s.unitsLab;
ss.Schedule_Type = "Laboratory";
ss.Number_Of_Hours = s.numberOfHoursLab;
}
sc.Subject_Schedules.Add(ss);
dc.Subject_Schedules.InsertOnSubmit(ss);
}
foreach (var sdl in s.department)
{
sd = new Subject_Department();
sd.Department_Number = sdl;
sc.Subject_Departments.Add(sd);
dc.Subject_Departments.InsertOnSubmit(sd);
}
sst = new Subject_Standing();
sst.Year = s.year;
sst.Semester = s.semester;
cu.Subject_Standings.Add(sst);
dc.Subject_Standings.InsertOnSubmit(sst);
if (s.yearStandingStatus)
{
prys = new Pre_Requisite_Year_Standing();
prys.Year_Standing = Convert.ToInt32(s.yearStanding.ToString().Substring(0, 1));
sc.Pre_Requisite_Year_Standings.Add(prys);
dc.Pre_Requisite_Year_Standings.InsertOnSubmit(prys);
}
else
{
if (s.prereq.Count == 0)
{
pr = new Pre_Requisite();
pr.Pre_Requisite_Code = null;
sc.Pre_Requisites.Add(pr);
dc.Pre_Requisites.InsertOnSubmit(pr);
}
else
{
foreach (var p in s.prereq)
{
pr = new Pre_Requisite();
pr.Pre_Requisite_Code = Convert.ToInt32(p);
sc.Pre_Requisites.Add(pr);
dc.Pre_Requisites.InsertOnSubmit(pr);
}
}
}
}
dc.Curriculums.InsertOnSubmit(cu);
dc.SubmitChanges();
return true;
}
如代码中所示,Curriculum
表在数据库中具有最高的层次结构,其他表将其主键继承到Subject_Curriculum,Pre_Requisite,Subject_Standing和Pre_Requisite_Year_Standing中。而Subject_Schedules和Subject_Department继承Subject_Curriculum的主键。我该怎么做才能一次插入所有表?
答案 0 :(得分:0)
我已经解决了我的问题。只需通过外键添加所有表,然后在循环末尾插入并提交更改。这将使该线程关闭。