C#アプリケーションでExecuteReaderを使用してテーブルからすべての列を取得しようとしています。Dbはpostgreです。テストするために、関数を使用してクエリを実行する方法を示したチュートリアルに従ってコンソールアプリケーションを作成しましたが、パラメータを渡すことはありません。コンソールアプリケーション関数テスト用
static void Main(string[] args)
{
// Connect to a PostgreSQL database
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;User Id=postgres; " +
"Password=pes;Database=pmc;");
conn.Open();
// Define a query
NpgsqlCommand command = new NpgsqlCommand("SELECT * from audit.exception_gl_accounts()", conn);
// Execute the query and obtain a result set
NpgsqlDataReader dr = command.ExecuteReader();
// Output rows
while (dr.Read())
Console.Write("{0}\t{1} \n", dr[0], dr[1]);
conn.Close();
}
}
ここNpgsqlCommandで、パラメーターなしのクエリを関数audit.exception_gl_accountsに送信しましたが、うまく機能しました。次に、このような関数にパラメーターを渡すにはどうすればよいですか。
"SELECT * FROM sms.get_accounts_info(@AccountNumber);
この関数を使用して5つの列すべてを取得し、それらのオブジェクトを取得しようとしています
public static string GetAccountInfo(string accountNumber)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;User
Id=postgres; " + "Password=pes;Database=pmc;");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM
sms.get_accounts_info(@AccountNumber); ", conn);
command.Parameters.AddWithValue("@AccountNumber", accountNumber);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
Console.Write("{0}\t{1} \n", dr[0], dr[1]);
return dr.ToString();
}
2番目のサンプルコードを使用すると、次のエラーが発生します。
{"accountNumber": "Npgsql.ForwardsOnlyDataReader"、 "balance":null、 "interestRate":0、 "accountName":null、 "accountType":null}
感謝するどんな助けでも。
詳細を更新
コントローラー
[HttpPost]
[ActionName("info")]
public IHttpActionResult GetAccountInfo([FromBody]AccountInfo
accountinfo)
{
accountinfo.accountNumber = BusinessLayer.Api.AccountHolderApi.GetAccountInfo
(accountinfo.accountNumber);
return Ok(accountinfo);
}
アカウント情報クラス
public class AccountInfo
{
public string accountNumber { get; set; }
public string balance { get; set; }
public int interestRate { get; set; }
public string accountName { get; set; }
public string accountType { get; set; }
}
嫌い
GetAccountsInfo
CREATE OR REPLACE FUNCTION sms.get_accounts_info(IN account_number_ character varying)
RETURNS TABLE(account_number character varying, account_name text, product character varying, interest_rate numeric, balance money) AS
$BODY$
BEGIN
RETURN QUERY(
SELECT a.account_number,
c.customer_name,
p.deposit_product_name,
a.interest_rate::numeric, deposit.get_balance(account_number_)
FROM deposit.account_holders a
JOIN core.customers_view c ON a.customer_id = c.customer_id
JOIN core.deposit_products p ON a.deposit_product_id = p.deposit_product_id
WHERE a.account_number = $1
);
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
ALTER FUNCTION sms.get_accounts_info(character varying)
OWNER TO postgres;
エンティティフレームワークがない場合は、データリーダーからAccountInfo
クラスのインスタンスに値を読み取るコードを記述する必要があります。
public static AccountInfo GetAccountInfo(string accountNumber)
{
AccountInfo result = null;
using(var conn = new NpgsqlConnection("..."))
{
conn.Open();
using(var command = new NpgsqlCommand("SELECT * FROM sms.get_accounts_info(@AccountNumber); ", conn))
{
command.Parameters.AddWithValue("@AccountNumber", accountNumber);
using(var dr = command.ExecuteReader())
{
if(dr.HasRows && dr.Read())
{
result = new AccountInfo {
accountNumber = dr["accountNumber"].ToString(),
balance = dr["balance"].ToString(),
interestRate = Convert.ToInt32(dr["interestRate"]),
accountName = dr["accountName"].ToString()
};
}
}
}
}
return result;
}
関数の戻り値の型がAccountInfo
、以前は文字列に変更されていることに注意してください。また、1つのレコードのみを読み取るように制限されています。1回の呼び出しsms.get_accounts_info
で複数のレコードが返される可能性がある場合、それは別の話です。これaccount_number
がaccount_holders
テーブルの主キーであると仮定しました。
いくつかの詳細には注意が必要です。たとえばbalance
、データベースにはお金がありますが、クラスには文字列があります。また、product
(データベース)とaccountType
(クラス)がどのように対応するのかわからなかったので省略しました。
データベース接続、コマンド、およびデータリーダーはIDisposable
、using
ブロックでラップする必要があります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加