.net - Inserting One to Many Entities using dapper -


i have following 2 classes , corresponding db tables. trying insert full object graph (student multiple courses). looking example on how 1 using dapper. id's auto-increment identity fields.

class

public class student {     public int id {get;set;}     public string name {get;set;}     public ienumerable<course> courses {get;set;} } public class course {     public int id {get;set;}     public string name {get;set;} } 

table

student
  id [int] (pk)
  name [varchar(50)]

studentcourse
  studentid [int] (fk)
  courseid [int] (fk)

course
  id [int] (fk)
  name [varchar(50)]

dapper has no general helper solve of ... quite easy wire in trivial case:

student student; // populate student ...   student.id = (int)cnn.query<decimal>(@"insert student(name) values(@name) select scope_identity()", student);  if (student.courses != null && student.courses.count > 0) {    foreach(var course in student.courses)    {       course.id = (int)cnn.query<decimal>(@"insert course(name) values(@name) select scope_identity()", course);    }    cnn.execute(@"insert studentcourse(studentid,courseid)  values(@studentid,@courseid)",     student.courses.select(c => new {studentid = student.id, courseid = c.id})); } 

one interesting note sample dapper able handle ienumerable input param , dispatch multiple commands each member of collection. allows efficient param reuse.

of course, stuff gets bit tricky if portions of graph exist in db.


Comments

Popular posts from this blog

php - How can I edit my code to echo the data of child's element where my search term was found in, in XMLReader? -

jQuery Ajax Render Fragments OR Whole Page -

java - Why is BlockingQueue.take() not releasing the thread? -