C# 如何返回与登录系统的用户具有相同城市代码的用户列表?
我发现很难返回与登录系统的用户具有相同城市(IdCity)的用户列表。 它不返回各种用户,而是创建冗余并返回登录的同一用户。 顺便说一句,我改变了这些模型的属性,因为它是用葡萄牙语写的 用户模型C# 如何返回与登录系统的用户具有相同城市代码的用户列表?,c#,.net,sql-server,asp.net-mvc,asp.net-web-api,C#,.net,Sql Server,Asp.net Mvc,Asp.net Web Api,我发现很难返回与登录系统的用户具有相同城市(IdCity)的用户列表。 它不返回各种用户,而是创建冗余并返回登录的同一用户。 顺便说一句,我改变了这些模型的属性,因为它是用葡萄牙语写的 用户模型 public partial class TblUser { [Key] public int UserId { get; set; } public string Name { get; set; } [NotMapped]
public partial class TblUser
{
[Key]
public int UserId { get; set; }
public string Name { get; set; }
[NotMapped]
public string City { get; set; }
public int IdCity { get; set; }
public virtual TblCity TblCity { get; set; }
}
城市模型
public partial class TblCity
{
[Key]
public int IdCity { get; set; }
public string City { get; set; }
}
程序
ALTER PROC [dbo].[SP_Citizen]
@IdCity int
AS
BEGIN
Select Name,t1.City from TblUser t1
join TblCity t2 on t2.IdCity = t1.IdCity
where t1.IdCity= @IdCity
END
行动
public ActionResult List()
{
List<TblUser> _users = new List<TblUser>();
using (SqlConnection con = new SqlConnection(Conexao.ConnectionString))
{
con.Open();
string sql = "SP_Citizen";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
var logged = User.Identity.Name;
int userId = db.TblUser.Where(x => x.Name== logged).FirstOrDefault().IdCity;
cmd.CommandType = CommandType.StoredProcedure;
TblUser citizen= new TblUser();
cmd.Parameters.AddWithValue("@IdCity", userId);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr != null)
{
while (dr.Read())
{
citizen.Name = dr["Name"].ToString();
citizen.City= dr["City"].ToString();
_users .Add(citizen);
}
}
}
}
}
return View(_usuarios);
}
public ActionResult List()
{
列表_用户=新列表();
使用(SqlConnection con=newsqlconnection(Conexao.ConnectionString))
{
con.Open();
字符串sql=“SP_公民”;
使用(SqlCommand cmd=newsqlcommand(sql,con))
{
var logged=User.Identity.Name;
int userId=db.TblUser.Where(x=>x.Name==logged);
cmd.CommandType=CommandType.storedProcess;
TblUser citizen=新TblUser();
cmd.Parameters.AddWithValue(“@IdCity”,userId);
使用(SqlDataReader dr=cmd.ExecuteReader())
{
如果(dr!=null)
{
while(dr.Read())
{
citizen.Name=dr[“Name”].ToString();
citizen.City=dr[“City”].ToString();
_用户。添加(公民);
}
}
}
}
}
返回视图(通常);
}
如何解决这个问题?这是一个常见的错误。在将公民添加到列表的循环之外,您只创建了一次公民的实例。结果是:同一个citizen实例多次添加到列表中,只需更改同一实例的值,直到到达末尾。在loop@Steve我很感激,这解决了为什么你需要加入的问题,你只过滤外键
t1.idCity
。无需检查dr!=null
我将模型简化为这两个属性,以便更方便地使用,因为最初完整的代码是用葡萄牙语编写的。顺便说一句,谢谢你的提示