简体   繁体   English

如何在 asp.net mvc web api 中使用导航属性

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

I am working on asp.net mvc 4 web api with EF code first model.我正在使用 EF 代码优先模型开发 asp.net mvc 4 web api。 I have a class with navigation property like like,我有一个带有导航属性的类,例如,

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

and my book class is like,我的书课就像,

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

Now i need to get list of branches so i write like,现在我需要获取分支列表,所以我这样写,

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

now i want to assign some data to book property in branch class so did like,现在我想将一些数据分配给分支类中的预订属性,所以我喜欢,

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

and now to get branch i have url like,现在为了获得分支,我有网址,

/api/branch/12

and is there any way to get particular book in a particular branch using url like有什么方法可以使用 url 获取特定分支中的特定书籍

/api/branch/12/book/567

to return book number 567 in branch number 12. please guide me.在 12 号分店归还 567 号书。请指导我。

You can use this kind of url to pass book to BranchController:您可以使用这种 url 将 book 传递给 BranchController:

/api/branch/12?book=567

Or you can create new route for your url或者您可以为您的网址创建新路线

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

Both options will invoke method like这两个选项都将调用方法,如

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

Also if you need to get book (it's not clear to me what you want - branch with single book, or just book from branch), then maybe BooksController is more appropriate place for this code.此外,如果您需要获取书籍(我不清楚您想要什么 - 使用单本书进行分支,或者只是从分支中预订),那么BooksController可能更适合此代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM