1

I am working on asp.net mvc 4 web api with EF code first model. 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

/api/branch/12/book/567

to return book number 567 in branch number 12. please guide me.

1 Answer 1

2

You can use this kind of url to pass book to 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you tell us more about the usage of OData and why they have introduced it? I thought OData was made to deal with navigation properties. Can you please explain?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.