避免使用硬编码字符串的一些 SqlKata 扩展方法





5.00/5 (5投票s)
SqlKata 很棒,但不得不使用硬编码字符串来表示表和字段,这并不是我的菜。
引言
一位同事最近向我介绍了 SqlKata,我发现它在处理 Dapper(SqlKata 在幕后使用的)时很有用,因为我可以编写流畅的类似 Linq 的语法,而不是硬编码 SQL 语句。
不幸的是,正如示例所示,这都使用了硬编码字符串
var query = db.Query("Books").OrderByDesc("PublishingDate");
这可不是我的菜!
一些基本的扩展方法
这个技巧向你展示了可以使用显式泛型参数编写的扩展方法,以避免硬编码字符串的风味。例如,我在另一篇文章中使用这个查询
var query = db.Query<Role>()
.Join<Role, UserRole>()
.Join<Role, EntityRole>()
.JoinChild<EntityRole, Entity>()
.Where<Entity>(nameof(Entity.TableName), entityName)
.Where<UserRole>(nameof(UserRole.UserId), userId);
而不是
var query = db.Query("Role")
.Join("UserRole", "Role.Id", "UserRole.RoleId")
.Join("EntityRole", "Role.Id", "EntityRole.RoleId")
.Join("Entity", "Entity.Id", "EntityRole.EntityId")
.Where("Entity.TableName", entityName)
.Where("UserRole.UserId", userId);
这需要四个扩展方法
public static class SqlKataExtensionMethods
{
public static Query Query<T>(this QueryFactory qf)
{
return qf.Query(typeof(T).Name);
}
public static Query Join<R, T>(this Query q)
{
var rname = typeof(R).Name;
var tname = typeof(T).Name;
return q.Join($"{tname}", $"{rname}.Id", $"{tname}.{rname}Id");
}
public static Query JoinChild<R, T>(this Query q)
{
var rname = typeof(R).Name;
var tname = typeof(T).Name;
return q.Join($"{tname}", $"{tname}.Id", $"{rname}.{tname}Id");
}
public static Query Where<T>(this Query q, string field, object val)
{
return q.Where($"{typeof(T).Name}.{field}", val);
}
}
当然,也需要为这个示例实现一些最小的模型。
public class Role { }
public class UserRole
{
public int UserId { get; set; }
}
public class EntityRole { }
public class Entity
{
public string TableName { get; set; }
}
结论
这就是全部。你可能从未听说过 SqlKata,直到几周前我也没听说过,使用它很好,但我讨厌不得不使用字符串常量。如果你正在使用 SqlKata 并喜欢这个概念,我相信你可以为 SqlKata 可以使用的其他函数添加更多的扩展方法。如果你写了一些,请在这里发布!
历史
- 2022 年 2 月 8 日:初始版本