我有一個小的Web Api方法。如何將GetBooks方法中的屬性與Automapper進行映射?我已經嘗試瞭解決方案here。在Web Api中使用帶有LINQ的Automapper獲取方法
我已經試過
return from c in db.Books select Mapper.Map<BookDTO>(c);
但它沒有工作。 這是我完整的代碼;
//GET: api/Books
public IQueryable<BookDTO> GetBooks()
{
var books = from b in db.Books
select new BookDTO()
{
Id = b.Id,
Title = b.Title,
AuthorName = b.Author.Name
};
return books;
}
Book.cs
public class Book
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
public int Year { get; set; }
public decimal Price { get; set; }
public string Genre { get; set; }
// Foreign Key
public int AuthorId { get; set; }
// Navigation property
public Author Author { get; set; }
}
BookDTO.cs
public class BookDTO
{
public int Id { get; set; }
public string Title { get; set; }
public string AuthorName { get; set; }
}
在此先感謝。
「但不成功」不是對問題的描述。 –
你說得對。我很着急,這就是我爲什麼這樣寫的。我的意思是我嘗試了我給出的鏈接上的方法。它沒有工作。我將這個代碼實施到我的。從上下文中的c返回。客戶 選擇Mapper.Map(c); –
oneNiceFriend