【问题标题】:how to work with navigation properties in asp.net mvc web api如何在 asp.net mvc web api 中使用导航属性
【发布时间】:2012-11-17 12:00:28
【问题描述】:

我正在使用 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();
}

现在我想为分支类中的 book 属性分配一些数据,所以很喜欢,

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

现在要获得分支,我有类似的 url,

/api/branch/12

有没有什么方法可以在特定的分支中使用类似 url 的方式获取特定的书

/api/branch/12/book/567

返回12号分行的567号书。请指导我。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-web-api


    【解决方案1】:

    您可以使用这种 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 可能更适合此代码。

    【讨论】:

    • 你能告诉我们更多关于 OData 的使用以及他们为什么引入它的信息吗?我认为 OData 是用来处理导航属性的。你能解释一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多