mvc 4无法隐式转换IEnumerable <anonymous> </anonymous>

时间:2013-07-29 16:41:52

标签: asp.net asp.net-mvc-4

我对mvc很新,并试图获得这个概念。我跟着this instruction来处理很多关系。但是我创建了一个接口和实体框架,并使用ninject将它们绑定在一起。我使用'群组'和'用户'代替“书籍”和“用户”(如教程中)。我读了许多关于同样错误的帖子,但他们似乎没有解决我的问题

public interface IGroups
    {
        IQueryable<Group> Groups { get; }
    }

public class EFGroups : IGroups
    {
        private EFDbContextMainDb1 context = new EFDbContextMainDb1();

        public IQueryable<Group> Groups
        {
            get;
            set;
        }
    }

 public class EFDbContextMainDb1 : DbContext
    {
        public DbSet<Group> tblGroup { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Group>().ToTable("tblGroup");

            base.OnModelCreating(modelBuilder);
        }

    }

public class GroupListViewModel
    {
        public IEnumerable<GroupNetworkUser> GroupNetworkUsers { get; set; }

    }

GroupListViewModel model = new GroupListViewModel
            {
                GroupNetworkUsers = testRepo.Groups.SelectMany(
                        group => group.Users,
                        (group, user) => new { 
                            userName = user.vch_NetworkID

                        }
                    )
            };

该错误适用于“GroupNetworkUsers = testRepo.Groups.SelectMany(...”。并说

Error   1   Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<Pho.Domain.Entities.GroupNetworkUser>'. An explicit conversion exists (are you missing a cast?) C:\visual_studio_project\pho\pho\Controllers\GroupsAndUsersController.cs    58  37  Pho.WebUI

2 个答案:

答案 0 :(得分:1)

您需要构建一个新的GroupNetworkUser对象。目前您正在构建一个匿名对象

GroupListViewModel model = new GroupListViewModel
        {
            GroupNetworkUsers = testRepo.Groups.SelectMany(
                    group => group.Users,
                    (group, user) => new GroupNetworkUser {  // <-- Changed this line
                        UserName = user.vch_NetworkID    
                    }
                ).ToList()
        };

答案 1 :(得分:0)

您需要将其转换为列表:

GroupListViewModel model = new GroupListViewModel
            {
                GroupNetworkUsers = testRepo.Groups.SelectMany(
                        group => group.Users,
                        (group, user) => new { 
                            userName = user.vch_NetworkID    
                        }
                    ).ToList()
            };