Search code examples
asp.netienumerableobjectdatasource

Returning a custom enumerable type from ObjectDataSource business class


This question might seem very basic but I am really very new to these aspects of C#. My apologies.

I am working on a ASP.NET 4 Web Forms application.

Here is my Book table

Book

BookID (pk) BookName AuthorID SubjectID Copies

Here is my Author table

Author

AuthorID(pk) AuthorName

Subject table

Subject

SubjectID(pk) SubjectName

I have generated ADO.NET Model classes from these tables in the database.

I have created a Business Class for my Book model (containing CRUD methods) so that I can use an ObjectDataSource to perform CRUD operations on Book.

Here is the get method of my Business Class

public static IEnumerable<Book> GetAllBooks()
    {
        var result = from author in db.Authors
                 join book in db.Books on new { AuthorID = author.AuthorID } equals new { AuthorID = book.AuthorID }
                 join subject in db.Subjects on new { SubjectID = book.SubjectID } equals new { SubjectID = subject.SubjectID }
                 select new { BookID = book.BookID, BookName = book.BookName, Copies = book.Copies, AuthorName = author.AuthorName };


        return result.ToList();
    }

The return type of this method is IEnumerable but since I am returning a list of anonymous objects now, this return type is invalid.

I know I can solve this by extending the Book model class so that it contains AuthorName and SubjectName, and then using that model class, but I want to avoid writing more code.

Is there any other way I can return this anonymous object list?


Solution

  • You could just return IEnumerable<dynamic> instead of IEnumerable<Book> if you really wanted the anonymous objects, but you're going in a bad direction here. When using the GetAllBooks method further up in your code you'll have no idea what properties these objects have and you'll have to go back to your business code to make sure - and even worse: The compiler won't help you at all catching typos. Try sticking to strongly typed objects.