2015-08-20 12 views
7

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; } 
} 
+1

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

+0

Inoltre, è importante disporre del contesto DB (variabile 'db' nel codice) quando hai finito. Il solito modo per farlo è con un blocco usando. –

+0

@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

risposta

1

Ecco l'essenza di aggiungere i dati relativi al database tramite Entity Framework:

class Program 
{ 
    static void Main(string[] args) 
    { 
     SchoolDBEntities dataContext = new SchoolDBEntities(); 
     //Create student object 
     Student student1 = new Student(); 
     student1.StudentName = "Student 01"; 
     //Create course objects 
     Cours mathCourse = new Cours(); 
     mathCourse.CourseName = "Math"; 
     Cours scienceCourse = new Cours(); 
     scienceCourse.CourseName = "Science"; 
     //Save courses to student 1 
     student1.Courses.Add(mathCourse); 
     student1.Courses.Add(scienceCourse); 
     //Save related data to database 
     //This will automatically populate join table 
     //between Students and Courses 
     dataContext.Students.Add(student1); 
     dataContext.SaveChanges(); 
    } 
} 

Un altro esempio: enter image description here

+0

grazie per aver risposto, ho provato il tuo metodo ma non riesco direttamente collega studente a modulo (es. student.module.add), c'è qualcosa che mi manca nella mia classe del modello o il mio database è impostato in modo errato? – cg91

+0

Ho notato in StudentCourses o StudentModule (o nella tabella di join) che se avessi altri campi nella tabella ad eccezione dei campi chiave primaria (come un id di tabella), EF non genererebbe correttamente per ragioni sconosciute. Assicurati anche che la tua chiave primaria nella tabella di join abbia entrambi i campi come chiave. Infine, un indicatore del fatto che EF ha fatto bene è che non vedrai la tabella dei join apparire nel diagramma delle relazioni EF. Sarà dedotto. In altre parole, vedrai Studente e Modulo ma non dovresti vedere la classe StudentModule nel diagramma EF. – Rod

+0

Ci scusiamo per la risposta tardiva, ora ho le mie tabelle configurate correttamente ma sto ancora ricevendo un problema con l'aggiunta al database, tutto sembra essere a posto quando aggiungo un punto di interruzione nella fase dataContext.Students.Add (student1) , C'è qualcos'altro che ho bisogno di cambiare? – cg91

Problemi correlati