简体   繁体   English

将对象从数据库添加到列表,使用 LINQ 到 SQL

[英]Add objects from database to a List, using LINQ to SQL

I have a table books and i want to put all of its contents into a List<book> (right now i'am stuck at adding a single element).我有一个 table books ,我想将它的所有内容放入一个List<book> (现在我坚持添加一个元素)。 I tried我试过了

public class DataContext
{
    LINQtoSQLDataContext db = new LINQtoSQLDataContext();
    List<book> books = new List<book>();
    public List<book> addBook()
    {
        books.Add((book)from book in db.books where book.bookID == 1 select book);
        return books;
    }
}

But when i try to set it as the source of my wpf dataGrid, it throws an error:但是当我尝试将它设置为我的 wpf dataGrid 的源时,它会抛出一个错误:

Unable to cast object of type 'System.Data.Linq.DataQuery`1[DataLayer.book]' to type 'DataLayer.book'.无法将“System.Data.Linq.DataQuery`1[DataLayer.book]”类型的 object 转换为类型“DataLayer.book”。

So the question is, how do i properly convert data from the database to a list?所以问题是,我如何正确地将数据从数据库转换为列表?

Just return the List of book as below:只需返回如下图书列表:

public List<book> addBook()
{
    return (from book in db.books 
        where book.bookID == 1 
        select book)
        .ToList();
}

And it's weird to name the method addBook as the method's outcome is to return a list of book.将方法命名为addBook很奇怪,因为该方法的结果是返回一本书列表。

Name it as: public List<book> GetBooks()将其命名为: public List<book> GetBooks()

While List<T>.Add(T) Method only allow to add single item to list, to add multiple items into list, you need List<T>.AddRange(IEnumerable<T>) Method .虽然List<T>.Add(T)方法只允许将单个项目添加到列表中,但要将多个项目添加到列表中,您需要List<T>.AddRange(IEnumerable<T>)方法

if I understand your problem correctly, the solution is simpler than expected, try making a where condition like this:如果我正确理解你的问题,解决方案比预期的要简单,请尝试像这样创建一个 where 条件:

public class DataContext
{
LINQtoSQLDataContext db = new LINQtoSQLDataContext();
List<book> books = new List<book>();
public List<book> addBook()
{
    books = db.book.Where(x => x.bookId == 1).ToList();
    return books;
} 
}

Just as sr28 pointed out, this will return an array.正如 sr28 指出的那样,这将返回一个数组。 You could either add the array to the books list.您可以将数组添加到books列表中。 I personally prefer using the method syntax.我个人更喜欢使用方法语法。

I don't really understand why you would add the book to this list.我真的不明白你为什么要把这本书添加到这个列表中。 But here you go. Since you already defined books you dont need to return it, you can simply add book to books .但是你在这里 go。因为你已经定义books你不需要返回它,你可以简单地 add book to books

public void AddBook()
{
    var book = db.books.FirstOrDefault(b => b.BookId == 1);
    books.add(book);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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