日期:2014-05-17  浏览次数:20787 次

WinForm三层架构,外键对象显示
Models实体类使用外键对象

public class UserType
{
    public Int32 Id { get; set; }
    public string TypeName { get; set; }
}
public class UserInfo
{
    public Int32 Id { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public UserType UserType { get; set; } 
}


DAL层

public IList<UserInfo> GetAllUser()
{
    IList<UserInfo> list = new List<UserInfo>();
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = "select * from UserInfo";
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                UserTypeService userTypeService = new UserTypeService();
                UserInfo userInfo = new UserInfo();
                userInfo.Id = (Int32)reader["Id"];
                userInfo.Name = (string)reader["Name"];
                userInfo.Gender = (string)reader["Gender"];
                userInfo.UserType = userTypeService.GetUserTypeById((Int32)reader["TypeId"]);//外键的处理
                list.Add(userInfo);
            }
        }