如何插入FK作为Dapper中的对象?

时间:2014-10-10 23:27:56

标签: .net dapper

我有一个对象Ticket,它具有User类型的属性。在数据库中,Ticket表具有到User表的FK。是否有一种简单的方法可以将故障单上已分配用户的 ID 传递给查询?

public class Ticket
{
    public int Id{get;}
    public User AssignedTo{get;set;}
}
public class User
{
    public int Id{get;}
}
public Ticket Save(Ticket newTicket)
{
    var sql = 
       @"
        Declare @localId int
        Insert into Ticket (AssignedTo)
        Values (@AssignedTo)

        Select @localId = CAST(SCOPE_IDENTITY() as int)

        Select
             Id
            ,AssignedTo
        From Ticket
        Where Id = @localId";
    var this.connection.Query<Ticket>(sql, newTicket);           
}

上述方法不起作用,因为newTicket.AssignedTo是User对象,但我需要的是存储用户的 ID 。是否有支持的方法与Dapper一起做到这一点?

1 个答案:

答案 0 :(得分:0)

我建议将此功能划分为两个功能。一个是将数据插入 Ticket 表并返回最后一个标识,第二个函数是使用该id检索记录。

注意:在您现有的功能中,您以错误的方式传递了参数。您可以使用现有功能执行此类操作 -

public Ticket Save(Ticket newTicket)
{
    string sql = string.Empty;
    sql = 
       @"
        Insert into Ticket (AssignedTo)
        Values (@AssignedTo);

        SELECT CAST(SCOPE_IDENTITY() as int);";

    var id = this.connection.Query<int>(sql, new { AssignedTo = newTicket.AssignedTo}).Single(); 

    sql = @"Select Id, AssignedTo
                From Ticket
                Where Id = @localId";
     return this.connection.Query<Ticket>(sql, new { localId = id }).Single();
}

但如果我假设您只想要2个字段IdAssignedTo,则无需再次执行选择查询。因此,在这种情况下,您可以做的是将新生成的id分配给现有对象newTicket,如下所示 -

public Ticket Save(Ticket newTicket)
{
    string sql = string.Empty();
    sql = 
       @"
        Insert into Ticket (AssignedTo)
        Values (@AssignedTo);

        SELECT CAST(SCOPE_IDENTITY() as int);";

    var id = this.connection.Query<int>(sql, new { AssignedTo = newTicket.AssignedTo}).Single(); 

    // Assign the last identity value to the ID proerpty of newTicket object
    newTicket.Id = id;

    // Return the existing object
    return newTicket
}
祝你好运......