使用列表从数据库接收行

本文关键字:数据库 列表 | 更新日期: 2023-09-27 18:24:51

我正在尝试在数据库连接时填充列表,我已经正确地关闭了MVVM,但我不知道如何定义列表,然后在该列表中,连接到数据库并填充字段。有人能帮忙吗?我的数据库运行良好。。。

UserRepository

public class UserRepository: IUserRepository
{
    private System.Data.SqlClient.SqlConnection connectionToDB;
    private System.Data.SqlClient.SqlDataAdapter dataAdapter;
    // Get the data set generated by the sqlStatement
    public System.Data.DataSet getDataSet(string sqlStatement)
    {
        System.Data.DataSet dataSet;
        // creates the object dataAdapter to manipulate a table from the database
        dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sqlStatement, connectionToDB);
        // create the dataset
        dataSet = new System.Data.DataSet();
        dataAdapter.Fill(dataSet);
        //return the dataSet
        return dataSet;
    }
    public List<Users> GetUsers()
    {
        List<Users> users;

        // Database connection to go here along with the list population
        // Something like this?
        //
        // new User
        //     ID = 
        //     FirstName = 
        //     LastName =   
        //  Users = CollectionViewSource.GetDefaultView(_users);

        return users;
    }

}

DBViewModel

public class DBDisplayViewModel
{
    private ObservableCollection<Users> users;
    public DBDisplayViewModel()
    {
        Load();
    }
    public IUserRepository UserRepository
    {
        get; set;
    }
    public ObservableCollection<Users> Users
    {
        get
        {
            if (users == null)
            {
                users = new ObservableCollection<Users>();
            }
            return users;
        }
        set
        {
            if (value != null)
            {
                users = value;
            }
        }
    }
    private void Load()
    {
        List<Users> users= UserRepository.GetUsers();
        Users= new ObservableCollection<Users>(users);
    }
}

Users

这只是定义了ID FirstName LastName属性

因此,分解它:需要创建UserRepository中注释掉的信息,以引入数据库连接和数据库值。有人能帮忙吗?非常爱!

使用列表从数据库接收行

看看下面的代码,会给出的想法

        public List<Users> GetUsers()
            {
                List<Users> users=new  List<Users> ();
                DataSet ds=getDataSet("Select FirstName,...... from Users")
                Users user;
                 foreach(DataRow row in ds.Tables[0].Rows)
                 {
                   user=new Users();
                   user.FirstName=row["firstname"].ToString();
                    ....
                    ....
                   users.Add(user)
                 }
                return users;
            }