在 SQL Server 上使用 LLBLGen 3.1(自助服务),如何执行自定义 SQL,例如:
- 从用户偏好中删除
- select * from UserPreference(例如,到数据表中)
在 SQL Server 上使用 LLBLGen 3.1(自助服务),如何执行自定义 SQL,例如:
刚刚注意到这个问题没有得到回答。使用自助服务,您可能会使用 TypedListDAO 类。
请参阅:生成的代码 - 获取 DataReaders 和投影,SelfServicing
TypedListDAO 类具有您对数据库执行 SQL 所需的功能,并且如果您需要,它可以自动为您对自定义类进行投影(请参阅文章)。
但基本上,(根据记忆,可能需要一些细微的调整),这就是您的代码可能的样子:
// inside the DaoClasses namespace of your generated project
TypedListDAO dao = new TypedListDAO();
// do it yourself, and use your project's connection string
string connectionString = CommonDaoBase.ActualConnectionString;
using (var conn = new SqlConnection(connectionString)) { }
// use a DbConnection directly
DbConnection connection = dao.CreateConnection();
// or
connection = dao.DetermineConnectionToUse(null);
DbCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM UserPreferences";
cmd.CommandType = CommandType.Text;
var reader = cmd.ExecuteReader(CommandBehavior.Default);
while (reader.Read()){}
reader.Close();
// use a datareader
IRetrievalQuery query = new RetrievalQuery(
new SqlCommand("SELECT * FROM UserPreferences"));
// or new RetrievalQuery(cmd);
// where you create the cmd using the dao connection
IDataReader reader = dao.GetAsDataReader(null, query,
CommandBehavior.CloseConnection);
while (reader.Read()){}
reader.Close();
// use a datatable - try something like this
// (BUT honestly, you might want to look at the custom projection
// into custom classes capability, or the data reader, instead of this)
DataTable dt = new DataTable();
dao.GetMultiAsDataTable(new EntityFields(0) /* can't be null, i don't think */,
dt, query, null);
// other methods
dao.ExecuteScalarQuery(query, null);
ActionQuery actionQuery = new ActionQuery(new SqlCommand("INSERT ..."));
dao.ExecuteActionQuery(actionQuery, null);
或者,使用 micro-orm 来执行您的 sql,并且只使用来自上面的 TypedListDAO 类的连接一些轻量级 micro-orms,例如:Dapper(1 cs 文件)、PetaPoco、Massive 等...
虽然您确实可以访问低级数据读取器等。我认为这有点违背了使用 ORM 的目的。如果您只想从集合中填充数据表(有或没有过滤),您可以使用静态方法 GetMultiAsDataTable(如果您想进行过滤,您可以将谓词表达式传递给该方法)。如果您想替换更复杂的 SQL(对报告非常有用),请查看动态列表功能:
http://www.llblgen.com/documentation/4.0/LLBLGen%20Pro%20RTF/hh_start.htm
QuerySpec 是一种更好的方式来指定动态查询并对其进行投影:
http://www.llblgen.com/documentation/4.0/LLBLGen%20Pro%20RTF/hh_start.htm