2

I'm doing my homework - making an web api 2 project with entity framework.

Here is my table layout, with m-2-m relationship between Singer and Genre tables.

enter image description here

My Genre is a table which I Use to get my singers list by alphabet (so Genre table get data from (ID: 1, Name: "A") to (ID: 26, Name: "Z")

Now I want to get all singers start with "H" (id=8)

public IQueryable<Singer> GetByGenre(int id)
    {            
        return db.Singers.Where(s => s.Genres.Any(g => g.ID == id));
    }

with this query:

http://localhost:6798/api/Singers/GetByGenre?id=8

But the result's strange - only the first result's show, while others return as "ref" ? I checked by create a "fake" list

var list = db.Singers.Where(s => s.Genres.Any(g => g.ID == id)).ToList();

and put debug on it, and it return correct 3 Singers ?

--

And as you see, I have other table (Song, Playlist, Video) which have a FK point to ID of my Singer , so how can I only return the Singer table's columns only (ID, NAME, IMAGE) without all other relationship data ( Playlists, Songs, Videos ...) ?

enter image description here

user3448806
  • 897
  • 10
  • 22

1 Answers1

2

Why does it include $ref in returned json result.

It is Json serializer who is including $ref to resolve the circular dependancies.

Look here for detail on this Stackoverflow answer -> Why is the Web Api returning empty json results with “$ref=”?

how can I only return the Singer table's columns only (ID, NAME, IMAGE) without all other relationship data ( Playlists, Songs, Videos ...) ?

You need to disable your lazy loading in the entity framework dbcontext.

something like this way:

db.Configuration.LazyLoadingEnabled = false;

For more information about lazy loading and serializer have a detailed look at this msdn article.

Community
  • 1
  • 1
Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62
  • Thank you ! I looked the detail and follow [this](http://johnnycode.com/2012/04/10/serializing-circular-references-with-json-net-and-entity-framework/) and add an `[JsonIgnore]` attribute on virtual property , now it's worked ! – user3448806 May 20 '15 at 08:03
  • 1
    @user3448806 Just for your note it would work only in case of serializing data in JSON. It would not work with xml data transfer. Look at [this](http://stackoverflow.com/a/11851461/1505865) SO thread for detail. I would recommend you to disable lazy loading or solution suggested in that answer instead of `[JsonIgnore]` attribute. – Jenish Rabadiya May 20 '15 at 09:05
  • Yep, but my WP8 client app also use Json to deserialize result, so it's fine for me. And I also forgot 1 question: can I and more column to result, i.e in this case - can I and the name of the genre in the Singer result like : "ID : 1 , Name : Henry, Genre: H , Image: ... " ? – user3448806 May 20 '15 at 09:13