I have the following DTO:
public int IdTableOne { get; set; }
public string ValueTableOne { get; set; }
public int IdTableTwo { get; set; }
public string ValueTableTwo { get; set; }
Also, I have two Models (TableOne & TableTwo) and I fill this models in my repository doing the following code:
return dbContext.TableOne;
At this point everything it's okay. TableOne & TableTwo are populated, but now I want to return the combination of these values into my DTO object (TableOneId is equal to TableTwoId, it's a relationship between both tables) for doing this I'm trying something like this:
public IEnumerable<TableOneAndTwoDTO> GetTableOneAndTwo()
{
List<TableOneAndTwoDTO> combination = new List<TableOneAndTwoDto>();
var t1 = myRepository.GetTableOne();
var t2 = myRepository.GetTableTwo();
var query = from p in t1
select new {
IdTableOne = p.Id,
ValueTableOne = p.Value,
};
foreach (var item in query)
{
combination.Add(new TableOneAndTwoDTO { IdTableOne = item.IdTableOne, ValueTableOne = item.ValueTableOne });
}
}
So my question is, how can I add the TableTwo values to my DTO only when IdTableOne = IdTableTwo.
CodePudding user response:
You can join your table results. Something like this:
var query = from p in t1
join j in t2 on p.IdTableOne equals j.IdTableTwo
select new { p, j };
And then you can add the join values to your DTO using something like this:
foreach (var item in query)
{
combination.Add(new TableOnwAndTwoDTO { IdTableOne = item.p.IdTableOne, IdTableTwo = item.j.IdTableTwo... })
}