LINQ JOIN two tables and viewing both columns - c#

I Have two tables
tblPhases
And
tblTruck
I JOINED these two but I can't seem to use both columns on both tables.
Phase.cs
public class Phases
{
public int Id { get; set; }
public int TruckId { get; set; }
public virtual RTrucks Truck { get; set; }
public string Checkin { get; set; }
public string ChassisPrep { get; set; }
public string Floor { get; set; }
public string Body { get; set; }
public string Paint { get; set; }
public string Finished { get; set; }
}
RTruck.cs
public class RTrucks
{
public int Id { get; set; }
public string ChassisManufacturer { get; set; }
public string ChassisModel { get; set; }
}
Service.cs
[OperationContract]
List<Phases> GetPhasesbyTruck(int TruckId);
Service.svc.cs
public List<Phases> GetPhasesbyTruck(int TruckId)
{
TruckDb db = new TruckDb();
List<Phases> r = new List<Phases>();
var join = from p in db.RTrucks
join t in db.Phases
on p.Id
equals t.TruckId
where t.Id == TruckId
select p;
foreach (var item in join)
{
r.Add(new Phases()
{
//this is not the actual coding but just a demonstration of what is
//actually happening
// Phases item like Id = tblTruck item like truckId
});
}
return r;
}
I cannot call the columns from the tblPhases table only from the tbltrucks table, and also how can I use the Phases.cs and RTruck.cs together in my foreach so I can access both class items?

First of all, following code
var join = from p in db.RTrucks
join t in db.Phases
on p.Id equals t.TruckId
select p;
is enough to make a join between two tables. you do not need to add an extra where clause to it. Secondly, you can either select properties from both tables as mentioned by Arianit in his answer or you can just select Phases as in above query and then you can access Truck through navigation properties like
foreach (var p in join){
int truckId = p.Truck.Id;
string chesis = p.Truck.ChassisManufacturer;
string model = p.Truck.ChassisModel;
}
The benefit of second approach is that you don't need a new class to populate properties from both tables. you can access all information through navigation properties.

try this:
var join = from p in db.RTrucks
join t in db.Phases
on p.Id equals t.TruckId
select new {TruckName = p.TruckName, //depends from your table column name
PhasesName = t.PhaseName
};
foreach (var item in join)
{
Console.WriteLine(item.TruckName + "\t" + item.PhaseName);
}
Remove the where from your linq

Related

LINQ data from view model using nested SQL [duplicate]

This question already has answers here:
LEFT JOIN in LINQ to entities?
(7 answers)
Closed 4 years ago.
I can access the data using the following TSQL:
select Sweets.*, Qty
from Sweets
left join (select SweetID, Qty from carts where CartID = '7125794e-38f4-4ec3-b016-cd8393346669' ) t
on Sweets.SweetID = t.SweetID
But I am not sure of how to achieve the same results on my web application. Does anyone know how this could be achievable using LINQ?
So far i have:
var viewModel = new SweetViewModel
{
Sweet = db.Sweets.Where(s => db.Carts.Any(c => c.SweetID == s.SweetID))
};
Edit: Sorry I should of specified that I am using a View model of the 2 classes:
View model:
public class SweetViewModel
{
public IEnumerable<Sweet> Sweet { get; set; }
public IEnumerable<Cart> Cart { get; set; }
//public Cart OrderQty { get; set; }
}
public class Sweet
{
public int SweetID { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
public string SweetName { get; set; }
public bool Singular { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public virtual ICollection<Cart> Carts { get; set; }
}
public class Cart
{
[Key]
public int RecordID { get; set; }
public string CartID { get; set; }
public int SweetID { get; set; }
public int PemixID { get; set; }
public int Qty { get; set; }
public System.DateTime DateCreated { get; set; }
public Sweet Sweet { get; set; }
public PreMix PreMix { get; set; }
}
The following will work
from sweet in db.Sweets
join cart in db.Carts
on sweet.SweetID equals cart.SweetID into swct
from sc in swct.DefaultIfEmpty()
select new { Sweet = sweet, Qty = sweet.Key == sc.Key ? sc.Qty : 0 }
var res=(from sweet in db.Sweets
join cart in db.Carts.Select(x=>new{x.SweetID,x.Qty})
on sweet.SweetID equals cart.SweetID
into r11
from r1 in r11.DefaultIfEmpty()
select new {sweet,r1})
.Select(x=>new
{
Sweet=x.sweet,
Qty=x.r1?.Qty
})
.ToList();
This will get you the equivalent result to your sql query.
res will be List<a> where a is anonymous class and it's structure will be
{Sweet,Qty}.
You should be using the LINQ join function.
For my example, I have also used an altered version of your SQL query which I believe to be identical:
SELECT sweets.*, carts.Qty
FROM sweets LEFT JOIN carts ON sweets.SweetID = carts.SweetID
WHERE carts.CartID = '7125794e-38f4-4ec3-b016-cd8393346669'
Then I translated this new query to LINQ with the JOIN function.
var cartId = '7125794e-38f4-4ec3-b016-cd8393346669'
var query = db.Sweets // table in the "from" statement
.GroupJoin(db.Carts, // all carts for that sweet will be joined into [sweets -> Cart[]]
cart => cart.SweetID, // the first part of the "on" clause in an sql "join" statement
sweet => sweet.SweetID, // the second part of the "on" clause)
(sweet, carts) => new { Sweet = sweet, Carts = cart }) // create new compound object
.SelectMany(
sweetsCarts => sweetsCart.Carts.DefaultIfEmpty(), //show the sweet even if there is no cart
(x,y) => new { Sweet = x.Sweet, Cart = y });
.Where(sweetsCart => sweetsCart.Cart.CartID == cartId); // restrict your cartID
Basically, the Join function makes a list of compound objects that contain a Sweet object and a Cart object with each list entry, hence why you can access sweetsCart.Cart.CartID or sweetsCart.Sweets.SweetID.
The name on the left side of the => can be anything you want by the way, it's just an identifier for LINQ. I chose to call it "sweetsCart".
The GroupJoin with the SelectMany makes it possible to do a Left Join.

Linq to SQL - Get Related Data

I've got some data that I need to return some of its related data and put it all in a model. I have all the appropriate fields setup in my model, and looks like this:
public class ComputerModel
{
public int MachineId { get; set; }
public int GroupId { get; set; }
public int SoftwareVersionId { get; set; }
public string GroupName { get; set; }
public string SoftwareVersion { get; set; }
public string IPAddress { get; set; }
public string HostName { get; set; }
public string MACAddress { get; set; }
public string Title { get; set; }
public bool IsIGMonitor { get; set; }
public string UpTime { get; set; }
public DateTime DateEntered { get; set; }
public string EnteredBy { get; set; }
public Nullable<DateTime> DateUpdated { get; set; }
public string UpdatedBy { get; set; }
public ICollection<MachineRole> MachineRoles { get; set; }
public ICollection<Role> Roles { get; set; }
}
Here's the linq statement I'm trying to use:
var query = (from m in unitOfWork.Context.Machines
join u in unitOfWork.Context.Users
on m.EnteredBy equals u.UserId into EntByUser
from EnteredByUser in EntByUser.DefaultIfEmpty()
join u2 in unitOfWork.Context.Users
on m.UpdatedBy equals u2.UserId into UpdByUser
from UpdatedByUser in UpdByUser.DefaultIfEmpty()
join g in unitOfWork.Context.Groups
on m.GroupId equals g.GroupId into Grp
from Groups in Grp.DefaultIfEmpty()
join s in unitOfWork.Context.SoftwareVersions
on m.SoftwareVersionId equals s.SoftwareVersionId into SW
from SoftwareVersions in SW.DefaultIfEmpty()
join mr in unitOfWork.Context.MachineRoles
on m.MachineId equals mr.MachineId into MachRoles
from MachineRoles in MachRoles.DefaultIfEmpty()
join r in unitOfWork.Context.Roles
on MachineRoles.RoleId equals r.RoleId into Rolz
from Rolz2 in Rolz.DefaultIfEmpty()
select new ComputerModel()
{
MachineId = m.MachineId,
GroupId = m.GroupId,
SoftwareVersionId = m.SoftwareVersionId,
GroupName = Groups.GroupName,
SoftwareVersion = SoftwareVersions.Version,
IPAddress = m.IPAddress,
HostName = m.HostName,
MACAddress = m.MACAddress,
Title = m.Title,
IsIGMonitor = m.IsIGMonitor,
UpTime = m.UpTime,
DateEntered = m.DateEntered,
DateUpdated = m.DateUpdated,
EnteredBy = EnteredByUser.FirstName + " " + EnteredByUser.LastName,
UpdatedBy = UpdatedByUser.FirstName + " " + UpdatedByUser.LastName,
MachineRoles = m.MachineRoles,
Roles = ?????
}).ToList();
I can get MachineRoles to populate but I cannot get Roles to populate. I've tried Roles = Rolz2 but Rolz returns a single instance of Role, not a collection.
How can I get this query to return Machines and the related data for both MachineRoles and Roles?
I've looked at the following articles but haven't had much luck:
This SO Article
Loading Related Data - MSDN
Using Include with Entity Framework
UPDATE
I notice if I remove my model and use an anonymous type, then I don't get any errors:
select new ()
{
GroupName = Groups.GroupName,
......
}).ToList();
But this doesn't help me in my project because I need to use a Model for the data.
If all the above tables are related via PK-FK relationship you can use linq lambda functions .Include() to include related tables and then use Navigation properties to access data.
If the tables are not related you can use LINQ left joins as shown in http://www.devcurry.com/2011/01/linq-left-join-example-in-c.html.
It looks like you need a mix of inner and left joins. The above example and only achieve inner joins.

LINQ - nested GroupJoin

I have looked at many LINQ examples on how to do GroupJoin. But I am not sure how to perform nested GroupJoin. Does somebody have any idea?
I have a following simple classes:
public class Subject
{
public int SubjectID { get; set;}
public string Name { get; set; }
}
public class SubjectStudent
{
public int SubjectStudentID { get; set; }
public int SubjectID { get; set; }
public int StudentID { get; set; }
}
public class StudentGrade
{
public int StudentGradeID { get; set;}
public int StudentID { get; set; }
public int GradeID { get; set; }
}
var subjects = (from s in Subject
join ss in SubjectStudent on s.SubjectID equals ss.SubjectID into SubjectStudents
select new
{
SubjectID = s.SubjectID,
Students = SubjectStudents
})
.ToList();
foreach (var subject in subjects)
{
foreach(var student in subject.Students)
{
//foreach(var grade in student.Grades)
//{
// I want to get grades for each subject.Students
//}
}
}
Can I have another GroupJoin after SubjectStudents, i.e. StudentGrades? I want to be able to iterate over StudentGrades in each subject.Students.
Thank you for any help.
Your data structure looks a bit confusing to me. Also, not sue if this is what you expect:-
var result = (from s in subjects
join ss in subjectStudents on s.SubjectID equals ss.SubjectID into SubjectStudents
select new
{
SubjectID = s.SubjectID,
Students = from ss in SubjectStudents
join g in studentsGrade on ss.StudentID equals g.StudentID
select new
{
StudentId = ss.StudentID,
GradeId = g.GradeID
}
})
.ToList();
Sample Fiddle

How to implement Entity Framework Code First join

I'm starting to use Entity Framework Code First.
Suppose to have such POCO's (ultimately simplified):
public class BortStructure
{
public Guid Id { get; set; }
public String Name { get; set; }
}
public class Slot
{
public Guid Id { get; set; }
public String Name { get; set; }
public BortStructure { get; set; }
}
public class SystemType
{
public Guid Id { get; set; }
public String Name {get; set; }
}
public class SlotSystemType
{
public Guid Id { get; set; }
public Slot Slot { get; set; }
public SystemType SystemType {get; set; }
}
and a context
public MyContext : DbContext
{
public DbSet<BortStructure> BortStructures { get; set; }
public DbSet<Slot> Slots{ get; set; }
public DbSet<SystemType> SystemTypes { get; set; }
public DbSet<SlotSystemType> SlotSystemTypes { get; set; }
}
I have a task to get BortStructure by Id with list of attached Slots, each one with list of systemTypes attached.
Using SQL allowed me to do that with some JOIN's:
SELECT BortStructures.Id, BortStructures.Name, Slots.Id,
Slots.Name, SystemType.Id, SystemType.Name FROM
((BortStructures LEFT JOIN Slots ON BortStructures.Id = Slots.BortStructureId)
LEFT JOIN SlotSystemTypes ON SlotSystemTypes.SlotId = Slots.Id)
LEFT JOIN SystemTypes ON SystemTypes.Id = SlotSystemTypes.SystemTypeId
WHERE BortStructures.Id='XXXXXX' ORDER BY Slots.Id, SystemType.Id
But with Entity Framework Code First I don't have any idea howto do that.
If I use
var slotSystemTypes = from sl in MyContext.SlotSystemTypes
where sl.Slot.BortStructure.Id = XXXXXX
orderby sl.Slot.Id, sl.SystemType.Id
select sl;
i, of course, will receive nothing if BortStructure consists of no Slots/Slots without any SystemTypes attached.
Instead of getting BortStructure with empty list of Slots/with Slots, each one with empty list of SystemTypes attached as I expect to get.
Is there any way to archive that with single LINQ query for my database configuration?
You can use join operator example:
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category
select new { Category = c, p.ProductName };
foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
more samples in: http://code.msdn.microsoft.com/LINQ-Join-Operators-dabef4e9

Linq Find Item by Primary Key and display Name(that lives in a different table)

I am displaying a record from my database. The record pulls data from other tables and uses a Int in the main table to represent the value so Item table has a Division equal to 1 and the Division table 1 = ALL . Now that i am displaying the records i am trying to turn the 1 into all. All the ID fields show the int. Which is what my code is telling it to do. But i am trying to display the name and when i do that i get a lot of red. It cannot find the name. CatagoryID should be CategoryName.
Hope that makes sense.
if (!IsPostBack)
{
string v = Request.QueryString["ContactID"];
int itemid;
int.TryParse(v, out itemid);
var customerInfo = GetCustomerInfo(itemid);
CONTACTID.Text = customerInfo[0].ContactID.ToString();
ContactTitle.Text = customerInfo[0].ContactTitlesID.ToString();
ContactNameB.Text = customerInfo[0].ContactName;
DropDownAddCategory.Text = customerInfo[0].CategoryID.ToString();
DDLAddDivision.Text = customerInfo[0].DivisionID.ToString();
ContactPhoneBox.Text = customerInfo[0].ContactOPhone;
ContactCellBox.Text = customerInfo[0].ContactCell;
ContactEmailBox.Text = customerInfo[0].ContactEmail;
CextB.Text = customerInfo[0].Ext;
}
private List<Solutions.Models.Contact> GetCustomerInfo(int itemid)
{
using (ItemContext context = new ItemContext())
{
return (from c in context.Contacts
where c.ContactID == itemid
select c).ToList();
}
}
This is the model
public class Contact
{
[ScaffoldColumn(false)]
public int ContactID { get; set; }
public System.DateTime ContactCreated { get; set; }
public string ContactName { get; set; }
public int? ContactTitlesID { get; set; }
public string ContactOPhone { get; set; }
public bool cApproved { get; set; }
public string User { get; set; }
public string ContactCell { get; set; }
public string ContactEmail { get; set; }
public int? DivisionID { get; set; }
public int? CategoryID { get; set; }
[StringLength(5)]
public string CExt { get; set; }
public virtual Division Division { get; set; }
public virtual Category Category { get; set; }
public virtual ContactTitle ContactTitle { get; set; }
public string Ext { get; set; }
}
With Entity Framework you can include related entities in query results:
return (from c in context.Contacts.Include("Catagory")
where c.ContactID == itemid
select c).ToList();
This will return contacts with Catagory objects: customerInfo.Catagory.CategoryName
BTW instead of returning list of contacts and selecting first one by index (thus possibly having index out of range exception), modify your method to return first contact (or default, if not found):
private Solutions.Models.Contact GetCustomerInfo(int itemid)
{
return (from c in context.Contacts.Include("Catagory")
where c.ContactID == itemid
select c).FirstOrDefault();
}
And use it this way:
var customerInfo = GetCustomerInfo(itemid);
if (customerInfo != null)
{
CONTACTID.Text = customerInfo.ContactID.ToString();
// etc
}
Are you using LINQ to SQL or Entity Framework? Check your model again and make sure the relationship between the two tables are setup correctly. The relationship may be missing from the model, and causing this problem.

Categories