Reputation: 638
I'm new to LINQ and Entity Framework and would appreciate some advice on the following scenario.
I have a entity model with two tables.
Travel_Request and Resource
Sample Fields
Travel_Request
Request_ID
Resource_ID
Resource
Resource_ID
Resource_Name
I would like to add the Resource_Name to the list when returning all the TRAVEL_REQUESTS
Thanks in advance
Upvotes: 3
Views: 27805
Reputation: 367
Use the Join:
Travel_Request.Join(Resource, tr => tr.ResourceId, r => r.ResourceId, (tr, r) => new { RequestId = tr.RequestId, ResourceId = tr.ResourceId, Name = r.ResourceName})
Or what a better practice would be is adding a Navigation property to TravelRequest. TravelRequest would look like this:
int RequestId { get; set; }
int ResourceId{ get; set; }
[ForeignKey("ResourceId")]
Resource Resource { get; set; }
This way you can use Include
DBContext.TravelRequests.Include("Resource").First().Resource.Name;
Include tells EF to get the Resource with the TravelerRequest
Upvotes: 1
Reputation: 1105
Hi you need to use the Linq join:
var data = from t in Travel_Request
join r in Resource on t.Resource_ID equals r.Resource_ID
select new
{
RequestId = t.Request_ID,
ResourceId = t.Resource_ID,
ResourceName = r.Resource_Name
};
If you already have an EF association then it could simply be:
var data = from t in Travel_Request
select new
{
RequestId = t.Request_ID,
ResourceId = t.Resource_ID,
ResourceName = t.Resource.Resource_Name
};
Upvotes: 7
Reputation: 2221
I would add a model that has all three then do something like.
var TravelRequests =
from p in Travel_Request
from r in Resource.where(Res => Res.Resource_ID == p.Resource_ID)
select new TravelModel{
requestID = p.requestID,
Resource_ID = p.Resource_ID,
ResourceName = r.ResourceName
};
But thats just an example of how I would do it and there might be better ways. Also syntax might be a little off but general idea is there.
Upvotes: 1
Reputation: 5812
You can query Travel_Request entity and use the navigation propety to do that.
var resultList = DbContext.Travel_Request.Resources.where(x=>x.Resource_Name =="Your string").ToList();
Upvotes: 1
Reputation: 1002
You will have to create a new object something like this.
var data = Travel_Request.Select(s=> new { Resource_Name = s.Recource.Resource_Name, Request_ID = s.Request_ID, Resource_ID = s.Resource_ID}).ToList();
As long as I've understood the question correctly this will work.
Upvotes: 2