【问题标题】:Inserting One to Many Entities using dapper使用 dapper 插入一对多实体
【发布时间】:2011-10-09 21:43:35
【问题描述】:

我有以下两个类和相应的数据库表。我正在尝试插入完整的对象图(有多个课程的学生)。我正在寻找一个关于如何使用 Dapper 来做到这一点的例子。 Id 是自动递增的身份字段。

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

表格

学生
ID [int] (pk)
名称 [varchar(50)]

学生课程
StudentId [int] (fk)
CourseId [int] (fk)

课程
ID [int] (fk)
名称 [varchar(50)]

【问题讨论】:

    标签: .net sql insert one-to-many dapper


    【解决方案1】:

    Dapper 没有通用的助手可以为你解决所有这些问题......但是在简单的情况下很容易连接:

    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}));
    }
    

    关于此示例的一个有趣的注意事项是,dapper 能够将 IEnumerable 作为输入参数处理,并为集合的每个成员分派多个命令。这允许有效的参数重用。

    当然,如果图的某些部分已经存在于数据库中,事情就会变得有些棘手。

    【讨论】:

    • 创建课程或学生课程出错时,创建的学生会怎样?
    猜你喜欢
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 2012-08-15
    • 2018-03-27
    相关资源
    最近更新 更多