Ho creato un metodo per aggiungere dati da un datatable a una tabella nel mio database tramite entity framework, tuttavia mi consente solo di popolare una tabella e voglio popolare più tabelle all'interno del un metodoAggiornamento datatable a più tabelle nel framework entità
Di seguito è il mio metodo che aggiunge alla tabella degli studenti e ho commentato la tabella dei moduli perché quando aggiungo questo in nessun dato viene trasferito al database. Qualcuno può consigliare un modo per popolare più tabelle all'interno di questo metodo?
Grazie
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;
}
}
Student Class
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; }
}
modulo di classe
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; }
}
Prendere Classe
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; }
}
cosa succede quando si rimuovere il commento che il codice? Ricevi un'eccezione, ha successo e le modifiche non vengono mantenute ... Potrebbe anche essere utile pubblicare la struttura di classe per queste 2 entità. – drneel
Inoltre, è importante disporre del contesto DB (variabile 'db' nel codice) quando hai finito. Il solito modo per farlo è con un blocco usando. –
@drneel quando annullo il codice che esegue ma nessuna tabella popola con i dati, attualmente i dati vengono compilati nella tabella degli studenti. Intendi postare i modelli per struttura di classe? – cg91