Reputation: 2711
I have a database with two tables. The first table contains an foreign key from the second table. In my MVC-project, i would like to display the value (stored in second table) instead of only the ID from the first table..
In SSMS i could do this with a join. But how do I do this in c#?
rec.Title = item.Title + " - " + item.AppointmentLength.ToString() + " mins" + " BehandlingsID " + ***item.BehandlingarId***;
//
item.BehandlingarId contains the ID which i would like to change to its corresponding value.
These are my two tabeles:
public class AppointmentDiary
{
public int ID { get; set; }
public DateTime DateTimeScheduled { get; set; }
public Behandlingar Behandling { get; set; }
public int? BehandlingarId { get; set; }
}
public class Behandlingar
{
public int BehandlingarId { get; set; }
public string Namn { get; set; }
public int Pris { get; set; }
public int Tid { get; set; }
}
List<DiaryEvent> result = new List<DiaryEvent>();
foreach (var item in rslt)
{
DiaryEvent rec = new DiaryEvent();
rec.EndDateString = item.DateTimeScheduled.AddMinutes(item.AppointmentLength).ToString("s");
rec.Title = item.Title + " - " + item.AppointmentLength.ToString() + " mins" + " BehandlingsID " + item.BehandlingarId;
}
Upvotes: 1
Views: 110
Reputation: 1279
Are you expecting something like this?
var result=AppointmentDiary.Where(i=>i.BehandlingarId==BehandlingarId).ToList;
This will give you the records that matches the BehandlingarId
in AppointmentDiary
table
Edit :
If you want the other way around.
If DB is your datacontext
var result=DB.Behandlingar.Where(i=>i.BehandlingarId == BehandlingarId).FirstorDefault().Nam;
Note: BehandlingarId here is the foreign key from AppointmentDiary.
say you want to access the nam
for BehandlingarId=1 then
var result=DB.Behandlingar.Where(i=>i.BehandlingarId == 1).FirstorDefault().Nam;
will give you the first record that matches the BehandlingarId==1
in the Behandlingar
table
You can put this snippet any where you want to access the nam
Hope this helps.
Upvotes: 1