【发布时间】:2015-08-20 17:25:55
【问题描述】:
我创建了一种通过实体框架将数据表中的数据添加到我的数据库中的表的方法,但是它只允许我填充一个表,并且我想在一个方法中填充多个表。
下面是我添加到学生表的方法,我已经注释掉了模块表,因为当我添加它时,没有数据传输到数据库。有人可以推荐一种我可以在此方法中填充多个表的方法吗?
谢谢
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; }
}
【问题讨论】:
-
取消注释该代码会发生什么?您是否遇到异常,是否成功并且更改不会持久化...发布这两个实体的类结构也可能会有所帮助。
-
另请注意,在完成后处理数据库上下文(代码中的
db变量)很重要。通常的方法是使用 using 块。 -
@drneel 当我取消注释它运行但没有表填充数据的代码时,目前数据确实填充在学生表中。您的意思是按类结构发布模型吗?
-
发布以下课程:ModuleEntities、Students 和 Module。学生或模块都不会持续存在,还是只是两者之一?
-
@drneel ModuleEntities 是我从中引用表的数据库的名称,似乎学生是我可以填充的唯一表。值得一提的是,我之前使用 CSV 文件填充了我的数据表?我添加的三个类是我希望填充的
标签: c# asp.net-mvc entity-framework datatable