我创建了一个方法,通过实体框架将数据从datatable添加到数据库中的表中,但它只允许我填充一个表,而我想在一个方法中填充多个表。
以下是我的方法向学生表添加内容,我已经注释掉了模块表,因为当我加入它时,没有数据传输到数据库。有人能推荐一种方法吗?我如何在这个方法中填充多个表?
谢谢
public Boolean ConvertDataTable(DataTable tbl)
{
string Feedback = string.Empty;
ModuleEntities db = new ModuleEntities();
// iterate over your data table
foreach (DataRow row in tbl.Rows)
{
student st = new student();
st.student_no = row.ItemArray.GetValue(0).ToString();
st.surname = row.ItemArray.GetValue(1).ToString();
st.firstname = row.ItemArray.GetValue(2).ToString();
db.students.Add(st);
//module mod = new module();
//mod.module_code = row.ItemArray.GetValue(3).ToString();
//mod.name = row.ItemArray.GetValue(4).ToString();
//db.modules.Add(mod);
}
try
{
db.SaveChanges();
Feedback = "Upload Successful";
return true;
}
catch
{
Feedback = "Upload Failed";
return false;
}
}
学生类
public partial class student
{
public student()
{
this.submits = new HashSet<submit>();
this.takes = new HashSet<take>();
this.lecturers = new HashSet<lecturer>();
}
public string student_no { get; set; }
public string surname { get; set; }
public string firstname { get; set; }
public virtual ICollection<submit> submits { get; set; }
public virtual ICollection<take> takes { get; set; }
public virtual ICollection<lecturer> lecturers { get; set; }
}
模块类
public partial class module
{
public module()
{
this.takes = new HashSet<take>();
this.lecturers = new HashSet<lecturer>();
}
public string module_code { get; set; }
public string name { get; set; }
public virtual ICollection<take> takes { get; set; }
public virtual ICollection<lecturer> lecturers { get; set; }
}
上课
public partial class take
{
public string student_no { get; set; }
public string module_code { get; set; }
public string grade { get; set; }
public virtual module module { get; set; }
public virtual student student { get; set; }
}