问题描述
我是 PostgreSQL 的新手,并试图从我刚刚在 Dapper 中创建的函数中获取结果。 Dapper 的 Query 功能成功,但结果没有映射到对象模型。
这是我正在使用的代码:
PostgreSQL 函数:
CREATE OR REPLACE FUNCTION GetUsers(Name VARCHAR)
RETURNS TABLE (ID INTEGER,Username VARCHAR,Password VARCHAR,IsActive BOOLEAN)
AS
$BODY$
SELECT ID,Username,Password,IsActive FROM Users WHERE Username = Name AND IsActive = true;
$BODY$
LANGUAGE sql;
C# 代码:
public List<User> GetUsers(string Name)
{
string Query = "SELECT GetUsers (@Name)";
var DynamicParams = new DynamicParameters();
DynamicParams.Add("@Name",Name);
using (var Conn = new NpgsqlConnection(ConnectionString))
return Conn.Query<User>(Query,param: DynamicParams,commandType: CommandType.Text).ToList();
}
public class User
{
public int ID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool IsActive { get; set; }
}
我上面写的代码正确吗? “返回表”会返回用户表的记录(超过 1 条记录)还是只返回 1 条记录?
当我在 PostgreSQL 中尝试使用相同的参数值时,它按预期返回结果:
SELECT GetUsers('Developer');
结果:
解决方法
对于那些想知道的人,上面的查询是:
import numpy as np
import pandas as pd
import itertools
#create random dataframe of integers
df = pd.DataFrame(np.random.randint(0,100,size=(100,4)),columns=['A','B','C','D'])
#turn ~20% of them into NaN's
df = df.mask(np.random.random(df.shape) < .2)
#upload the no nulls data first
df.dropna().to_sql(table_name,conn,index=False,if_exists='append')
#get column names into list
cols = list(df.columns)
#create powerset of column names
p_set = itertools.chain.from_iterable(
itertools.combinations(cols,r) for r in range(1,len(cols)))
#iterate through all combinations of column names
for null_cols in p_set:
#determine what the columns are where we DO want values
not_null_cols = list(set(cols) - set(null_cols))
#filter original dataframe to rows where ALL the null_cols are
# null AND ALL the other cols have a non-null value
sub_df = df[df[list(null_cols)].isnull().all(1) &
df[list(not_null_cols)].notnull().all(1)]
#if this dataframe has values,send it to database
if len(sub_df) > 0:
#sub_df still has all columns at this point,only keep the
# ones with values
sub_df = sub_df[not_null_cols]
sub_df.to_sql(table_name,if_exists='append')
将作为名称为“GetUsers”的对象返回,并且将包含多个值,因此您必须在模型中添加以下代码才能正确获取 Dapper 映射。
string Query = "SELECT GetUsers (@Name)";
或者,您可以对 Dapper 执行以下查询以正确映射它,而无需添加“GetUsers”对象。
public class User
{
/* the rest of the model */
public object GetUsers { get; set; }
}
上面的查询将返回列而不是具有多个值的单个对象,如在 PostgreSQL 中编写的函数,在这种情况下,列是:ID、用户名、密码、IsActive