使用Dapper的速记插入 - 无需指定列

时间:2016-05-20 13:09:02

标签: c# sql sql-server database-connection dapper

有没有办法用dapper进行简写插入,而不指定所有列?我只想传入一个对象或一个对象列表。我的所有模型名称都与db中的表名匹配。

我正在创建一个功能,可以将一个实体从另一个实体复制而不想指定列,因为如果将来添加另一个字段,代码管理将会很少。

StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT *");
sql.AppendLine("FROM Product ");
sql.AppendLine("WHERE Id = @Id");
Product source = connection.Query<Product>(sqlCopy.ToString(), 
    new
    {
        Id = productId
    }, transaction).SingleOrDefault();


// INSERT source entity here without specifying INSERT INTO (COLUMNS)

1 个答案:

答案 0 :(得分:2)

您是否尝试过使用Dapper.SimplerCRUD(https://github.com/ericdc1/Dapper.SimpleCRUD)或Dapper.Contrib(https://github.com/StackExchange/Dapper/tree/master/Dapper.Contrib)?

插入Dapper.SimplerCRUD(来自github示例):

public static int Insert(this IDbConnection connection, object entityToInsert)

使用示例:

[Table("Users")]
public class User
{
   [Key]
   public int UserId { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int Age { get; set; }

  //Additional properties not in database
  [Editable(false)]
  public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } }
   public List<User> Friends { get; set; }
   [ReadOnly(true)]
   public DateTime CreatedDate { get; set; }
}

var newId = connection.Insert(new User { FirstName = "User", LastName = "Person",  Age = 10 });  

Contrib(来自github示例): 插入方法

插入一个实体

connection.Insert(new Car { Name = "Volvo" });

或实体列表。

connection.Insert(cars);