0

I understand that you cannot return a generic list in a standard .asmx webservice. However I believe you can return an array []. My problem is converting the list to an array. Can someone help? I have a bunch of Business Object that already return a type List so I am not open to converting the original objects to Arrays...

Here is my WebMethod.

   [WebMethod]

    public Book[] GetBooksList()

    {

        List<Book> obj = new List<Book>();
        BookDA dataAccess = new BookDA();       

        obj = dataAccess.GetBooksAll().ToArray(); //error 1 here on conversion

    return obj; //error 2 here

    }  

Error I receive is 2 fold : Cannot implicitly convert type BookDTO.Book [] to GenericList

Cannot implicitly convert type GenericList to

midnightCoder
  • 75
  • 1
  • 11
  • Possible duplicate of: http://stackoverflow.com/questions/4093754/webmethod-returning-generic-list – Didaxis Jan 05 '12 at 18:17

1 Answers1

0

Because you already declared that obj was a list, not an array. Try this instead:

[WebMethod]
public Book[] GetBooksList()
{
    BookDA dataAccess = new BookDA();

    List<Book> obj = dataAccess.GetBooksAll();

    return obj.ToArray();
}

Or better yet:

[WebMethod]
public Book[] GetBooksList()
{
    var dataAccess = new BookDA();

    var obj = dataAccess.GetBooksAll().ToArray();

    return obj;
}
Didaxis
  • 8,486
  • 7
  • 52
  • 89
  • 1
    I tried your 1st suggestion return obj.ToArray(); and I get the error not on that line but on the line obj = dataAccess.GetBooksAll() -> Cannot implicitly convert type 'Generic.List' to 'Generic.List ' – midnightCoder Jan 05 '12 at 18:30
  • 1
    Well there's your problem. A BookDTO.Book is not the same thing as a BookService.Book. You'll need to straighten that out first. – Didaxis Jan 05 '12 at 18:33
  • 1
    Hmm. Works fine in my Console App, but in the .asmx.cs file I receive the error Cannot implicitly convert type 'Generic.List' to 'Generic.List '. Has to be something so simple but cant seem to find it..Any ideas anyone?? – midnightCoder Jan 05 '12 at 18:59
  • 1
    Ok figured it out. My Service calss name was Book same as my object. So if anyone needs to return Array [] in webservice from List use return obj.ToArray(); it works! – midnightCoder Jan 05 '12 at 19:05
  • 1
    Isn't that the same as the first suggestion in my answer? Absolutely your problem was a naming conflict between BookDTO.Book and BookService.Book, which I pointed out in my comment. This is why you should properly separate your business objects into a separate assembly from any client code (i.e., your console app or your web app). Not to mention that if you really do have a DTO type, you SHOULD be returning that from your WebMethod, and not a business object from your domain model. – Didaxis Jan 05 '12 at 19:07
  • Yes you are correct. My bo is in a separate asssembly. Thanks ErOx! – midnightCoder Jan 05 '12 at 19:17