Tôi đã tạo một phương thức để thêm dữ liệu từ một dữ liệu vào bảng trong cơ sở dữ liệu của tôi thông qua khung thực thể, tuy nhiên nó chỉ cho phép tôi điền một bảng và tôi muốn điền nhiều bảng trong một phương pháp.Cập nhật dữ liệu cho nhiều bảng trong khung thực thể
Dưới đây là phương pháp của tôi thêm vào bảng học sinh và tôi đã nhận xét ra bảng mô-đun bởi vì khi tôi thêm điều này trong không có dữ liệu được chuyển đến cơ sở dữ liệu. Ai đó có thể giới thiệu một cách tôi có thể cư trú nhiều bảng trong phương pháp này?
Cảm ơn
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;
}
}
Sinh Lớp
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; }
}
Mô-đun lớp
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; }
}
Tham Lớp
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; }
}
Điều gì xảy ra khi bạn bỏ ghi chú mã? Bạn có được một ngoại lệ, nó thành công và những thay đổi không được duy trì ... Nó cũng có thể hữu ích để đăng cấu trúc lớp cho 2 thực thể đó. – drneel
Cũng lưu ý điều quan trọng là phải vứt bỏ bối cảnh DB của bạn (biến 'db' trong mã của bạn) khi bạn đã hoàn thành nó. Cách thông thường để thực hiện điều này là sử dụng khối. –
@drneel khi tôi bỏ ghi chú mã nó chạy tuy nhiên không có bảng điền dữ liệu, hiện tại dữ liệu không có trong bảng học sinh. Bạn có ý định đăng các mô hình theo cấu trúc lớp học không? – cg91