是否有更短,更好和优化的方法来从SQL数据库填充此列表

时间:2018-07-01 23:48:46

标签: c# entity-framework linq

我得到了这段代码,它可以正常工作。但是我觉得有更好的方法来做到这一点。

    namespace Repositories
    {
        public class AuthorRepository : IAuthorRepository
        {
            public List<Author> GetAllFromRepo()
            {
                using (AppContext myDB = new AppContext())
                {
                    List<Author> authorsFromRepo = new List<Author>();
                    foreach (var item in myDB.Authors)
                    {
                        authorsFromRepo.Add(new Author()
                        {
                            Books = new List<Book>(),
                            ID = item.ID,
                            FirstName = item.FirstName,
                            LastName = item.LastName
                        });
                    }
                    return authorsFromRepo.ToList();
                }
            }
        }
    }

当我尝试以下方法时:

 public List<Author> GetAllFromRepo()
    {
        using (AppContext myDB = new AppContext())
        {
            List<Author> authorsFromRepo = new List<Author>();

            authorsFromRepo = myDB.Authors.ToList();
            return authorsFromRepo;
        }
    }

我总是会收到此错误:

  

值不能为null。   参数名称:来源   异常详细信息:System.ArgumentNullException:值不能为null。   参数名称:来源   源错误:第33行:返回authors.Select(x => new AuthorViewModel()

有帮助吗? 错误带给我的模型

namespace Services
{
    public class AuthorService : IAuthorService
    {
        private readonly IAuthorRepository _AuthorRepository;

        public AuthorService(IAuthorRepository authorRepository)
        {
            _AuthorRepository = authorRepository;
        }
        public List<AuthorViewModel> GetAll()
        {
            List<Author> authors = _AuthorRepository.GetAllFromRepo();

            return authors.Select(x => new AuthorViewModel()
            {
                ID = x.ID,
                FullName = $"{x.FirstName } {x.LastName} ",
                Books = x.Books.Select(g => new BookViewModel()
                {
                    ID = g.ID,
                    Name = g.Name
                }).ToList()
            }).ToList();

        }
    }
}

要再次添加,如果我使用第一个代码示例,则一切正常。 当我尝试较短的东西

 return myDB.Authors.ToList();

我得到了错误。

当我更改为:

return authors.Select(x => new AuthorViewModel()
       {
        ID = x.ID,
        FullName = $"{x.FirstName } {x.LastName} ",
        Books = {}
        }).ToList();

然后可以使用...但这意味着它不会阅读作者的书...

1 个答案:

答案 0 :(得分:0)

我不得不将Authors的模型更改为

extern

所以当x.Books为空时,它不会给我任何错误。