Reputation: 3
I have 2 tables as below:
MatchDetails:
MatchId MatchName TeamId1 TeamId2
1 Test 1 2
TeamDetails:
TeamId TeamName
1 MyTeam
2 YourTeam
Now I want a list of all the matches.
In my MatchController
what I am trying to do is:
CricketEntity db = new CricketEntity();
[HttpGet]
public ActionResult GetAllMatches()
{
List<C_MatchDetails> listMatches = db.C_MatchDetails.ToList();
return Json(new
{
success = "true",
Message = "Data retrive successfully",
ResposeData = listMatches
},
JsonRequestBehavior.AllowGet);
}
This is returning only match details. I want the match details with the team details filled in it.
Something like:
MatchId MatchName TeamId1 TeamName1 TeamId2 TeamName2
1 Test 1 MyTeam 2 YourTeam
Thanks in advance.
Upvotes: 0
Views: 57
Reputation: 2818
It makes life a lot easier if you add navigation properties to the MatchDetails
class.
If you set you set your MatchDetails
class up as follows:
public class MatchDetails{
public int MatchId { get; set; }
public string MatchName { get; set; }
public int TeamId1 { get; set; }
public int TeamId2 { get; set; }
public virtual TeamDetails Team1 { get; set; } // One new navigation property
public virtual TeamDetails Team2 { get; set; } // Another new navigation property
}
And define the relationships in your context class using Fluent API as follows:
modelBuilder.Entity<MatchDetails>()
.HasRequired(m => m.Team1)
.WithMany()
.HasForeignKey(m => m.TeamId1);
modelBuilder.Entity<MatchDetails>()
.HasRequired(m => m.Team2)
.WithMany()
.HasForeignKey(m => m.TeamId2);
Then your LINQ becomes much simpler and requires no projections:
var listMatches = db.C_MatchDetails
.Include(x => x.Team1)
.Include(x => x.Team2)
.ToList();
Upvotes: 1
Reputation: 3192
You can try like this.
MatchDetails.Join(TeamDetails, x => new {x.TeamId , x.TeamId},
y => new {y.TeamId1 , y.TeamId2}, (x, y) => new
{
x.name;
//////
////
});
Upvotes: 0
Reputation: 27
Use Include so EF brings back references to teams when you get the data, something like:
... db.C_MatchDetails.Include(x => x.Team1).Include (x => x.Team2).To list();
Upvotes: 0
Reputation: 795
You can create stored procedure on the db that returns joined table. like this ->>
Select m.MatchId, m.MatchName, m.TeamId1, t.TeamName as TeamName1, m.TeamId2, t2.TeamName as TeamName2
from MatchDetails m inner join TeamDetails t on m.TeamId1=t.TeamId Inner join TeamDetails t2 on m.TeamId2=t2.TeamId
Upvotes: 0