从ObjectDataSource业务类返回自定义可枚举类型 [英] Returning a custom enumerable type from ObjectDataSource business class
问题描述
这个问题可能看起来很基本但我对C#的这些方面真的很新。我很抱歉。
我正在使用ASP.NET 4 Web窗体应用程序。
这是我的书桌
预订
--------------- ---
BookID(pk)
BookName
授权书
主题ID
副本
这是我的作者表
作者
-----------
AuthorID(pk)
作者姓名
主题表
主题
---------------
SubjectID(pk)
主题名称
我从数据库中的这些表生成了ADO.NET模型类。
我为我的Book模型创建了一个Business Class(包含CRUD方法),这样我就可以使用ObjectDataSource在Book上执行CRUD操作。
这是获取我的商务舱的方法
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();
}
此方法的返回类型是IEnumerable但是因为我返回了现在匿名对象列表,这个返回类型是无效的。
我知道我可以通过扩展Book模型类来解决这个问题,使它包含AuthorName和SubjectName,然后使用该模型类,但我想避免编写更多代码。
有没有其他方法可以返回这个匿名对象列表?
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?
推荐答案
我会创建如下的新类
I would create new class like below
public class BookWithAuthorName
{
public int BookID { get; set; }
// add all properties of Book and
public string AuthorName { get; set; }
}
你的方法没有类型安全返回类型
no you have type safe returning type for your method
public static IEnumerable<bookwithauthorname> 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 BookWithAuthorName{ BookID = book.BookID, BookName = book.BookName, Copies = book.Copies, AuthorName = author.AuthorName };
return result.ToList();
}
这篇关于从ObjectDataSource业务类返回自定义可枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!