[已解决],gzaxx 的回答。
即使在数据库中一个成员没有被插入两次,在数据网格中它显示了两次!我有一张我添加会员的表格,还有一张我添加会员付款的表格。当我向成员添加超过 1 笔付款时,该成员会在网格中显示两次。
要列出我正在使用的成员:
public List<Member> ListMembers()
{
List<Member> Members = new List<Member>();
string STATUS = "SELECT m.Id, m.Name,m.Surname, m.EntryDate, p.EndDay FROM Members m left join Payments p on m.Id = p.MemberId order by m.Id ";
using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand(STATUS, sqlConnection))
{
var sqlReader = sqlCommand.ExecuteReader();
while (sqlReader.Read())
{
var member = new Member
{
Id = Convert.ToInt32(sqlReader["Id"]),
Name = sqlReader["Name"].ToString(),
Surname = sqlReader["Surname"].ToString(),
EntryDate = Convert.ToDateTime(sqlReader["EntryDate"])
};
if (sqlReader["EndDay"].ToString() != "")
if (Convert.ToDateTime(sqlReader["EndDay"]) < DateTime.Today)
{
member.Status = Status.Unpaid.ToString();
}
else
{
member.Status = Status.Paid.ToString();
}
Members.Add(member);
}
}
}
return Members;
}
对于付款:
public List<Payment> ListPayments(Payment entity)
{
List<Payment> Payments = new List<Payment>();
string SELECT = "SELECT * FROM Payments WHERE MemberId = @MemberId";
using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand(SELECT, sqlConnection))
{
sqlCommand.Parameters.Add("@MemberId", SqlDbType.Int).Value = entity.MemberId;
var sqlReader = sqlCommand.ExecuteReader();
while (sqlReader.Read())
{
var payment = new Payment
{
Id = Convert.ToInt32(sqlReader["Id"]),
MemberId = Convert.ToInt32(sqlReader["MemberId"]),
Amount = Convert.ToDecimal(sqlReader["Amount"]),
StartDay = Convert.ToDateTime(sqlReader["StartDay"]),
EndDay = Convert.ToDateTime(sqlReader["EndDay"])
};
Payments.Add(payment);
}
}
}
return Payments;
}
如果成员没有付款,它的状态列将显示 NOTHING。如果会员有一次付款,它将显示其状态。但是如果我添加一个新的付款(超过一个),数据网格将显示相同的成员等于它在网格上的付款。我究竟做错了什么 ???