How do I execute a SQL statement with parameters i

2019-06-13 00:13发布

问题:

I want to execute SQL statement with paraemeters in ServiceStack ormlite

String.Format("SELECT OBJECT_ID(@name)", name);

I want the best way.

回答1:

If you need the POCO result you can use:

List<Person> results = db.SqlList<Person>("SELECT * FROM Person WHERE Age < @age", new { age=50});

Reference: https://github.com/ServiceStack/ServiceStack.OrmLite#typed-sqlexpressions-with-custom-sql-apis



回答2:

You can use SqlScalar<T> where T is int. Then simply pass an anonymous object with your parameter.

int result = db.SqlScalar<int>("SELECT OBJECT_ID(@name)", new { name = "SomeName" });

to select a List<T> of POCO type rather than an int you can use:

var results = db.SqlList<User>("SELECT * FROM Users WHERE Name = @name", new { name = "SomeName" });

You can read more here in the official documentation examples.

Hope this helps.