简体   繁体   中英

How to assign a output list to ListView in c# 3 layered architecture

I am working on one application which has a three layer architecture using EF Code First module.

  1. UI Layer (UI)
  2. Business Logic Layer (BLL)
  3. Data Access Layer (DAL)

Using LINQ I am retrieving the data from database in DAL and passing it to BLL and from BLL to UI

Ex.

In DAL

    public object ReadUsers()
    {
        var users = db.Users.Select(u => new { u.UserName, u.IsDisable, u.FullName, u.Descriprion }).ToList();
        return users;
    }

in BLL

    public object ReadUsers()
    {
        return _userDAL.ReadUsers();
    }

and in UI - Assigning the list of Users to ListView

        var users = _userBLL.ReadUsers();
        users.ToList()
            .ForEach(x => lvUserRoleGroup.Items.Add(
                new ListViewItem(
                    new string[] { x.UserName, x.IsDisable.ToString(), x.FullName, x.Descriprion }))
                );

But it is throwing an error

Error 1 'object' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Can anyone tell me how to show the output in ListView ? It is working fine with DataGridView as below -

        var users = _userBLL.ReadUsers();
        dataGridView1.DataSource = users;

When you are returning users from your methods,it casts to object .So when you call ToList() method,in object 's reference there is not that method.You must cast it back to your object's type.And because you have anonymous type,you need to create your custom class with fields x.UserName, x.IsDisable.ToString(), x.FullName, x.Descriprion and everywhere instead of anonymous type use your Custom Type and then cast to that object of List<CustomClass>

Or change objects like this

This will be your class

class CustomClass
{
   public string UserName {get ;set ;}
   public bool IsDisable  {get ;set ;}
   public string FullName {get ;set ;}
   public string Description {get ;set ;}
}

In DAL

public List<CustomClass> ReadUsers()
{
        var users = db.Users.Select(u => new CustomClass{ UserName = u.UserName, IsDisable = u.IsDisable, FullName = u.FullName, Description u.Descriprion }).ToList();
        return users;
}

in BLL

public List<CustomClass> ReadUsers()
{
    return _userDAL.ReadUsers();
}

and in UI - Assigning the list of Users to ListView

List<CustomClass> users = _userBLL.ReadUsers();

            users.ForEach(x => lvUserRoleGroup.Items.Add(
                new ListViewItem(
                    new string[] { x.UserName, x.IsDisable.ToString(), x.FullName, x.Descriprion }))
                );

将对System.Linq的引用添加到失败的项目。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM