簡體   English   中英

如何在 asp.net mvc web api 中使用導航屬性

[英]how to work with navigation properties in asp.net mvc web api

我正在使用 EF 代碼優先模型開發 asp.net mvc 4 web api。 我有一個帶有導航屬性的類,例如,

public class Branch
{
[Key]
public int Id{get; set;}
public List<book> books{get; set;}
}

我的書課就像,

public class book
{
[Key]
public int id{get; set;}
public string Name{get; set;}
}

現在我需要獲取分支列表,所以我這樣寫,

public IQuerable<branch> GetBranches(int branchid)
{
  return context.school.where(m=>m.id==branchid).ToList().AsQuerable();
}

現在我想將一些數據分配給分支類中的預訂屬性,所以我喜歡,

context.school.ToList().ForEach(m=>m.books=GetBooks(branchid));

現在為了獲得分支,我有網址,

/api/branch/12

有什么方法可以使用 url 獲取特定分支中的特定書籍

/api/branch/12/book/567

在 12 號分店歸還 567 號書。請指導我。

您可以使用這種 url 將 book 傳遞給 BranchController:

/api/branch/12?book=567

或者您可以為您的網址創建新路線

config.Routes.MapHttpRoute(
    name: "BranchBooksApi",
    routeTemplate: "api/branch/{id}/book/{bookId}",
    defaults: new { controller = "Branch" });

這兩個選項都將調用方法,如

public book Get(int id, int bookId)
{
    //...
}

此外,如果您需要獲取書籍(我不清楚您想要什么 - 使用單本書進行分支,或者只是從分支中預訂),那么BooksController可能更適合此代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM