Unable to show the contents of the second table in Fiddler - c#

I am using Linq to join 2 tables. I am able to get the contents of the first table but getting the second table as null. How can I extract the contents of the second table also into a single JSON object. My code is below:
public static IEnumerable<Tbl_Students> GetAllStudents()
{
StudentDBEntities dataContext = new StudentDBEntities();
var query = (from student in dataContext.Tbl_Students
join subject in dataContext.Tbl_Subjects on student.Roll_Number equals subject.Roll_Number
select new
{
Roll_Number = student.Roll_Number,
FirstName = student.FirstName,
LastName = student.LastName,
Class = student.Class,
Gender = student.Gender,
Science = subject.Science,
Social = subject.Social,
Mathematics = subject.Mathematics,
Total = subject.Total
}).ToList().Select(s => new Tbl_Students
{
Roll_Number = s.Roll_Number,
FirstName = s.FirstName,
LastName = s.LastName,
Class = s.Class,
Gender = s.Gender
});
return query;
}
The two table structures are:
Student
public class Student
{
public int Roll_Number { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Class { get; set; }
public string Gender { get; set; }
}
Subject
class Subject
{
public int Roll_Number { get; set; }
public int Science { get; set; }
public int Social { get; set; }
public int Mathematics { get; set; }
public int Total { get; set; }
}
I am getting everything except the subjects in Fiddler.
Adding the image

Problem is that you are never populating Tbl_Subjects from your query. I have updated your query to populate Tbl_Subjects.
public static IEnumerable<Tbl_Students> GetAllStudents()
{
StudentDBEntities dataContext = new StudentDBEntities();
var query = (from student in dataContext.Tbl_Students
join subject in dataContext.Tbl_Subjects on student.Roll_Number equals subject.Roll_Number
select new
{
Roll_Number = student.Roll_Number,
FirstName = student.FirstName,
LastName = student.LastName,
Class = student.Class,
Gender = student.Gender,
Science = subject.Science,
Social = subject.Social,
Mathematics = subject.Mathematics,
Total = subject.Total
}).ToList().Select(s => new Tbl_Students
{
Roll_Number = s.Roll_Number,
FirstName = s.FirstName,
LastName = s.LastName,
Class = s.Class,
Gender = s.Gender,
Tbl_Subjects = new Tbl_Subjects ()
{
Science = s.Science,
Social = s.Social,
Mathematics = s.Mathematics,
Total = s.Total
Roll_Number = s.Roll_Number
};
});
return query;
}

Related

Entity Framework Core: FromSqlInterpolated(). An item with the same key has already been added. Key: Id

I want to get a list of my friends' stories. It didn't work through LINQ, but I was able to write a good SQL query that really works and returns what I need. I use .NET 7 & EF Core 7.
int userId = 1;
StoryContainerRto test = await _context.StoryContainer
.FromSqlInterpolated($#"SELECT s."Id", s."AuthorId", u."Id", u."AccountHeaderUrl", u."AvatarUrl", u."Description", u."Email", u."IsAuthorOfQualityContent", u."IsDeleted", u."IsInShadowBan", u."IsVerifiedProfile", u."LinkInBio", u."MedalsAmount", u."Name", u."Nickname", u."PasswordHash", u."PasswordSalt", u."PhoneNumber", u."PhoneNumberPrefix", u."PhoneNumberVerefied", u."RegistrationDateTime", u."TelegramId", u."TelegramVerifyingChatId"
FROM ""StoryContainer"" as s
INNER JOIN ""StoryContentRefs"" as scr ON scr.""StoryId"" = s.""Id""
LEFT JOIN ""User"" as u ON u.""Id"" = s.""AuthorId""
LEFT JOIN ""StoryContentRefRtoUserRto"" as whoView ON whoView.""ViewedId"" = {userId} AND whoView.""ViewedStoriesId"" = scr.""Id""
WHERE s.""AuthorId"" IN (
SELECT u.""Id""
FROM ""UserFriend"" as f, ""User"" as u
WHERE
CASE
WHEN f.""FirstUserFriendId"" = {userId}
THEN f.""SecondUserFriendId"" = u.""Id""
WHEN f.""SecondUserFriendId"" = {userId}
THEN f.""FirstUserFriendId"" = u.""Id""
END
)
AND scr.""CreateTimestamp"" >= NOW() - '1 day'::INTERVAL
AND scr.""IsDelete"" = false").ToListAsync();
Output:
System.ArgumentException: An item with the same key has already been added. Key: Id
If you execute this code, the SQL query will be identical (given that the SQL query is lightweight. It just gets the story and the author, but does not get the rest of the information, because it is needed only for clarity)
StoryContainerRto entity = await _context.StoryContainer
.AsNoTracking()
.Include(e => e.Author)
.Where(e => e.AuthorId == 1)
.ToListAsync();
Generated SQL (note the duplication of the "Id" column):
SELECT s."Id", s."AuthorId", u."Id", u."AccountHeaderUrl", u."AvatarUrl", u."Description", u."Email", u."IsAuthorOfQualityContent", u."IsDeleted", u."IsInShadowBan", u."IsVerifiedProfile", u."LinkInBio", u."MedalsAmount", u."Name", u."Nickname", u."PasswordHash", u."PasswordSalt", u."PhoneNumber", u."PhoneNumberPrefix", u."PhoneNumberVerefied", u."RegistrationDateTime", u."TelegramId", u."TelegramVerifyingChatId"
FROM "StoryContainer" AS s
INNER JOIN "User" AS u ON s."AuthorId" = u."Id"
WHERE s."AuthorId" = 1
User table:
[Table("User")]
public class UserRto
{
[Key] public int Id { get; set; }
[Required] public string Nickname { get; set; }
public string? Email { get; set; }
[Required] public byte[] PasswordHash { get; set; }
[Required] public byte[] PasswordSalt { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
public string? LinkInBio { get; set; }
public int MedalsAmount { get; set; }
public string? AvatarUrl { get; set; }
public bool IsDeleted { get; set; }
public bool? IsVerifiedProfile { get; set; }
public bool? IsAuthorOfQualityContent { get; set; }
public bool IsInShadowBan { get; set; }
public DateTime RegistrationDateTime { get; set; }
public string? PhoneNumberPrefix { get; set; }
public string? PhoneNumber { get; set; }
public bool PhoneNumberVerefied { get; set; }
public string? TelegramId { get; set; }
public string? TelegramVerifyingChatId { get; set; }
public string? AccountHeaderUrl { get; set; }
public List<FriendInvitationRto> FriendInvitationsSent { get; set; }
public List<FriendInvitationRto> FriendInvitationsReceived { get; set; }
public List<UserFriendRto> FirstFriends { get; set; }
public List<UserFriendRto> SecondFriends { get; set; }
public List<StoryContentRefRto> ViewedStories { get; set; }
public StoryContainerRto StoryContainer { get; set; }
}
Story table:
[Table("StoryContainer")]
public class StoryContainerRto
{
public int Id { get; set; }
public int AuthorId { get; set; }
public UserRto Author { get; set; }
public List<StoryContentRefRto> Items { get; set; }
}
How do I complete the request? I understand that the fact is that 3 columns of "Id" come from three tables. But at the same time, if you look at the request generated by EF itself, then there are also 2 "Ids". How do I execute such a request correctly?
https://makolyte.com/ef-core-select-queries-involving-multiple-table/
There is an example of code using INNER JOIN like mine. I do not know why the same approach does not work for me
I also applied the AS operator to all the "Id" columns, but in that case I get this error:
The required column 'Id' was not present in the results of a 'FromSql' operation
I was able to solve this problem using a direct SQL query to the database, and then analyzed the information myself
List<StoryRto> friendsStories = new();
using (NpgsqlCommand command = (NpgsqlCommand)(_context as PotokContext)!.Database.GetDbConnection().CreateCommand())
{
command.CommandText = $#"SELECT s.*, scr.*, u.*, whoView.""ViewedId"" as ""IViewThis""
FROM ""Stories"" as s
INNER JOIN ""StoryContentRefs"" as scr ON scr.""StoryId"" = s.""Id""
INNER JOIN ""User"" as u ON u.""Id"" = s.""AuthorId""
LEFT JOIN ""StoryContentRefRtoUserRto"" as whoView ON whoView.""ViewedId"" = 1 AND whoView.""ViewedStoriesId"" = scr.""Id""
WHERE s.""AuthorId"" IN (
SELECT u.""Id""
FROM ""UserFriend"" as f, ""User"" as u
WHERE
CASE
WHEN f.""FirstUserFriendId"" = 1
THEN f.""SecondUserFriendId"" = u.""Id""
WHEN f.""SecondUserFriendId"" = 1
THEN f.""FirstUserFriendId"" = u.""Id""
END
)
AND scr.""CreateTimestamp"" >= NOW() - '1 day'::INTERVAL
AND scr.""IsDelete"" = false
LIMIT {count}
OFFSET {skipCount}";
(_context as PotokContext)!.Database.OpenConnection();
using (var reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
// Stories table
int storyId = reader.GetInt32(0);
int authorId = reader.GetInt32(1);
// StoryContentRefs table
int scrId = reader.GetInt32(2);
int scrStoryId = reader.GetInt32(3);
string scrStoryContentRef = reader.GetString(4);
bool scrIsDelete = reader.GetBoolean(5);
DateTime scrCreateTimestamp = reader.GetDateTime(6);
// UserTable
int userId = reader.GetInt32(7);
string userNickname = reader.GetString(8);
string? userEmail = reader.IsDBNull(9) ? null : reader.GetString(9);
// password hash and salt will not be included
string? userName = reader.IsDBNull(12) ? null : reader.GetString(12);
string? userDescription = reader.IsDBNull(13) ? null : reader.GetString(13);
string? userLinkInBio = reader.IsDBNull(14) ? null : reader.GetString(14);
int userMedalsAmount = reader.GetInt32(15);
string? userAvatarUrl = reader.IsDBNull(16) ? null : reader.GetString(16);
bool userIsDeleted = reader.GetBoolean(17);
bool? userIsVerifiedProfile = reader.IsDBNull(18) ? null : reader.GetBoolean(18);
DateTime userRegistrationDateTime = reader.GetDateTime(19);
bool? userIsAuthorOfQualityContent = reader.IsDBNull(20) ? null : reader.GetBoolean(20);
string? userPhoneNumber = reader.IsDBNull(21) ? null : reader.GetString(21);
string? userPhoneNumberPrefix = reader.IsDBNull(22) ? null : reader.GetString(22);
bool userPhoneNumberVerified = reader.GetBoolean(23);
string? userTelegramId = reader.IsDBNull(24) ? null : reader.GetString(24);
string? userTelegramVerifyingChatId = reader.IsDBNull(25) ? null : reader.GetString(25);
bool userIsInShadowBan = reader.GetBoolean(26);
string? userAccountHeaderUrl = reader.IsDBNull(27) ? null : reader.GetString(27);
// WhoViewStory relation
int? iViewThis = reader.IsDBNull(28) ? null : reader.GetInt32(28);
UserRto user = new()
{
Id = userId,
Nickname = userNickname,
Email = userEmail,
Name = userName,
Description = userDescription,
LinkInBio = userLinkInBio,
MedalsAmount = userMedalsAmount,
AvatarUrl = userAvatarUrl,
IsDeleted = userIsDeleted,
IsVerifiedProfile = userIsVerifiedProfile,
RegistrationDateTime = userRegistrationDateTime,
IsAuthorOfQualityContent = userIsAuthorOfQualityContent,
PhoneNumber = userPhoneNumber,
PhoneNumberPrefix = userPhoneNumberPrefix,
PhoneNumberVerefied = userPhoneNumberVerified,
TelegramId = userTelegramId,
TelegramVerifyingChatId = userTelegramVerifyingChatId,
IsInShadowBan = userIsInShadowBan,
AccountHeaderUrl = userAccountHeaderUrl
};
List<UserRto> viewed = new();
if (iViewThis != null) viewed.Add(user);
StoryContentRefRto storyContentRef = new()
{
Id = scrId,
StoryId = scrStoryId,
ContentRefs = scrStoryContentRef,
IsDelete = scrIsDelete,
CreateTimestamp = scrCreateTimestamp,
Viewed = viewed
};
if (friendsStories.FirstOrDefault(e => e.Id == scrStoryId) == null)
{
// Create new
StoryRto story = new()
{
Id = storyId,
AuthorId = authorId,
Author = user,
Items = new() { storyContentRef }
};
friendsStories.Add(story);
}
else
{
// Add to existing
StoryRto story = friendsStories.First(e => e.Id == scrStoryId);
story.Items.Add(storyContentRef);
}
}
}
else
{
Console.WriteLine("No rows found.");
}
}
}

Get all Column of foreign key table along with main table column in LINQ

I am trying to get list of all subjects for all students(Subject list within student list).
Subject table(SubjectPk,StudentId,SubjectName,Description,AddedOn,AddedBy) has many subject for the single student.
I have tried this: No Luck
var data = (from st in db.Student
join sub in db.Subject on st.StudentId equals sub.st.StudentId into subjectsList
select new StudentModel
{
Name = st.Name,
Class= st.Class,
RollNo = st.RollNo,
SubjectList = subjectsList //public ILIst<Subject> SubjectList {get;set;}
}).ToList();
and this : No Luck
var data = (from st in db.Student
select new StudentModel
{
Name = st.Name,
Class= st.Class,
RollNo = st.RollNo,
SubjectList = db.Subject.where(s.StudentId == st.StudentId).ToList()
}).ToList();
and
var data = (from st in db.Student
let subjectsList = db.Subject.where(s.StudentId == st.StudentId).ToList()
select new StudentModel
{
Name = st.Name,
Class= st.Class,
RollNo = st.RollNo,
SubjectList = subjectsList
}).ToList();
Since this looks like a Many to many relationship between Student and Subject, ideally you should have a different table that reference both students and subjects. so you should have something like this:
public class Student{
public int Id{get; set;}
public string StudentName{get; set;}
public IList<StudentsSubjects> Subjects{get; set;}
// other properties
}
public class Subject{
public int Id{get; set;}
public string SubjectTitle{get; set;}
public IList<StudentsSubjects> Students{get; set;}
// other properties
}
public class StudentsSubjects{
public int Id{get; set;}
public int StudentId{get; set;}
public int SubjectId{get; set;}
public DateTime DateAdded{get; set;}
}
Then if you are using entity framework you do
data = db.Student.Include(s => s.Subjects).ToList()
then use a foreach loop and get the data you want.
Your first attempt looks ok except that i removed sub.st.StudentId to sub.StudentId
var data = (from st in db.Student
join sub in db.Subject on st.StudentId equals
sub.StudentId into subjectsList
select new StudentModel
{
Name = st.Name,
Class= st.Class,
RollNo = st.RollNo,
SubjectList = subjectsList //public ILIst<Subject> SubjectList {get;set;}
}).ToList();
Maybe you can add ToList() for subjectList. Please try this:
var data = (from st in db.Student
join sub in db.Subject on st.StudentId equals sub.st.StudentId into subjectsList
select new StudentModel
{
Name = st.Name,
Class= st.Class,
RollNo = st.RollNo,
SubjectList = subjectsList.ToList() //public ILIst<Subject> SubjectList {get;set;}
}).ToList();
Please check the below code it's working
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var employees = new List<Employees>() {
new Employees(){ Id = 1,CompanyName="Google",EmpCode="12345", EmployeeName="Ravindra"},
new Employees(){ Id = 2,CompanyName="Microsoft",EmpCode="123456", EmployeeName="Vishal"},
new Employees(){ Id = 3,CompanyName="IBM",EmpCode="123457", EmployeeName="Kishore"},
new Employees(){ Id = 4,CompanyName="Capgemini",EmpCode="123458", EmployeeName="Amit"}
};
var technologies = new List<Technology>()
{
new Technology(){EmployeeId=1,TechnologyName="Data Structure"},
new Technology(){EmployeeId=1,TechnologyName="Dotnet 6"},
new Technology(){EmployeeId=1,TechnologyName="SQL"},
new Technology(){EmployeeId=1,TechnologyName="Azure"},
new Technology(){EmployeeId=1,TechnologyName="React"},
new Technology(){EmployeeId=1,TechnologyName="Angular"},
new Technology(){EmployeeId=2,TechnologyName="Dotnet 1"},
new Technology(){EmployeeId=2,TechnologyName="Dotnet 2"},
new Technology(){EmployeeId=2,TechnologyName="Dotnet 3"},
new Technology(){EmployeeId=2,TechnologyName="Dotnet 4"},
new Technology(){EmployeeId=2,TechnologyName="Dotnet 5"},
new Technology(){EmployeeId=2,TechnologyName="Dotnet 6"},
new Technology(){EmployeeId=2,TechnologyName="Dotnet 7"},
new Technology(){EmployeeId=2,TechnologyName="Dotnet 8"},
new Technology(){EmployeeId=2,TechnologyName="Development"},
new Technology(){EmployeeId=3,TechnologyName="DAA"},
new Technology(){EmployeeId=4,TechnologyName="Math"},
new Technology(){EmployeeId=5,TechnologyName="English"}
};
var result = (from st in employees
select new ShowModel
{
EmployeeName = st.EmployeeName,
CompanyName = st.CompanyName,
EmpCode = st.EmpCode,
TechnologyList = technologies.Where(x => x.EmployeeId == st.Id).ToList()
}).ToList();
foreach (var final in result)
Console.WriteLine("Name: {0} | Class: {1} | RollNo: {2} | TechnologyList Count: {3} ", final.EmployeeName, final.CompanyName, final.EmpCode, final.TechnologyList.Count);
}
public class Employees
{
public int Id { get; set; }
public string EmployeeName { get; set; }
public string CompanyName { get; set; }
public string EmpCode { get; set; }
}
public class Technology
{
public string TechnologyName { get; set; }
public int EmployeeId { get; set; }
}
public class ShowModel
{
public string EmployeeName { get; set; }
public string CompanyName { get; set; }
public string EmpCode { get; set; }
public IList<Technology> TechnologyList { get; set; }
}
}

Insert results of 2 collections into a new model

I have a wpf c# app.
I have to list collections.
I want to join these 2 lists and return the results that match a criteria.
I want the result to be loaded into a new list/model.
This is my code so far:
var Results = from j in res
join c in Customer.GetBaseData() on j.CustomerRef equals c.CustomerRef
where j.JobStatusRef == jobStatusRef
select new {
c.CustomerRef,
c.CustomerId,
c.Add1,
c.Town,
c.FName,
c.SName,
j.DateReq,
j.JobId,
j.JobRef,
j.JobStatus
};
This is my destination model:
public class CustomerJobs
{
public int JobId { get; set; }
public string CustomerRef { get; set; }
public string DateReq { get; set; }
public string JobRef { get; set; }
public string JobStatus { get; set; }
public int CustomerId { get; set; }
public string SName { get; set; }
public string FName { get; set; }
public string Add1 { get; set; }
public string Town { get; set; }
}
I do not know how to do this final step?
Instead of creating an anonymous type with new { ... }, directly use your model in the select:
var Results = from j in res
join c in Customer.GetBaseData() on j.CustomerRef equals c.CustomerRef
where j.JobStatusRef == jobStatusRef
// Note the "new CustomerJobs" part.
select new CustomerJobs {
c.CustomerRef,
c.CustomerId,
c.Add1,
c.Town,
c.FName,
c.SName,
j.DateReq,
j.JobId,
j.JobRef,
j.JobStatus
};
When you select in linq you can specify the type of the object like:
var Results = from j in res
join c in Customer.GetBaseData() on j.CustomerRef equals c.CustomerRef
where j.JobStatusRef == jobStatusRef
select new CustomerJobs {
CustomerRef = c.CustomerRef,
CustomerId = c.CustomerId,
Add1 = c.Add1,
Town = c.Town,
FName = c.FName,
SName = c.SName,
DateReq = j.DateReq,
JobId = j.JobId,
JobRef = j.JobRef,
JobStatus = j.JobStatus
};

Cannot initialize type 'PeopleModel' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

I have a method that aims to fill a PersonModel from OleDB;
public IEnumerable<PeopleModel> GetPeopleDetails()
{
var constr = ConfigurationManager.ConnectionStrings["dbfString"].ConnectionString;
using (var dbfCon = new OleDbConnection(constr))
{
dbfCon.Open();
using (var dbfCmd = dbfCon.CreateCommand())
{
dbfCmd.CommandText = "SELECT pp_firstname, pp_surname, pp_title, pp_compnm, pp_hmaddr1, pp_hmaddr2, pp_hmtown, pp_hmcounty, pp_hmpcode, pp_spouse, pp_children FROM people ORDERBY pp_surname";
using (var myReader = dbfCmd.ExecuteReader())
{
var peopleList = new List<PeopleModel>();
while (myReader.Read())
{
var details = new PeopleModel
{
details.Firstname = myReader[0].ToString(),
details.Lastname = myReader[1].ToString(),
details.Title = myReader[2].ToString(),
details.Company = myReader[3].ToString(),
details.Addr1 = myReader[4].ToString(),
details.Addr2 = myReader[5].ToString(),
details.Town = myReader[6].ToString(),
details.County = myReader[7].ToString(),
details.Spouse = myReader[8].ToString(),
details.Children = myReader[9].ToString(),
};
peopleList.Add(details);
}
return peopleList;
}
}
}
}
This code is pretty much identical to the method I am using to fill a companies details, which works no problem. Here is the PeopleModel I am using to build a person.
namespace SdcDatabase.Model
{
public class PeopleModel
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Title { get; set; }
public string Company { get; set; }
public string Addr1 { get; set; }
public string Addr2 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Spouse { get; set; }
public string Children { get; set; }
}
}
Although the companies method has worked fine previously, I am now getting the following error when I try to build my project after implementing the People code: Cannot initialize type 'PeopleModel' with a collection initializer because it does not implement 'System.Collections.IEnumerable'
I really am at a lost cause with this as it is working in an almost identical method for a Company.
Correct syntax, without details. in the assignments in the initializer:
var details = new PeopleModel
{
Firstname = myReader[0].ToString(),
Lastname = myReader[1].ToString(),
Title = myReader[2].ToString(),
Company = myReader[3].ToString(),
Addr1 = myReader[4].ToString(),
Addr2 = myReader[5].ToString(),
Town = myReader[6].ToString(),
County = myReader[7].ToString(),
Spouse = myReader[8].ToString(),
Children = myReader[9].ToString(),
};

Linq join 3 list <T>

I have three lists that I need to join together
class Person
{
public int PersonID{ get; set; }
public string FirstName{get; set;}
public string LastName {get; set;}
}
class Traffic
{
public DateTime Date{ get; set; }
public int PersonID;
public int TrafficID;
}
class TrafficType
{
public int TrafficID { get; set; }
public string Description { get; set; }
}
List<Person> Persons=GetPersons();
List<TrafficType> TrafficTypes=GetTrafficTypes();
List<Traffic> Traffics=GetTraffics();
I need an output like:
PersonID FirstName LastName Date Description
1001 David ... 2011/07/19 sample description
from person in Persons
from traffic in traffics
from trafficType in trafficTypes
where trafficType.TrafficID = traffic.TrafficID
where traffic.PersonID = person.PersonID
select new
{
PersonID = person.PersonID,
....
}
var result = Persons.Join(
Traffics,
person => person.PersonID,
trafic => trafic.PersonID,
(person, trafic) => new
{
PersonId = person.PersonID,
FirstName = person.FirstName,
LastName = person.LastName,
Date = trafic.Date,
TraficId = trafic.TrafficID
}).Join(
TrafficTypes,
a => a.TraficId,
traficType => traficType.TrafficID,
(a, traficType) => new
{
PersonId = a.PersonId,
FirstName = a.FirstName,
LastName = a.LastName,
Date = a.Date,
Description = traficType.Description
});
Here's a complete code sample with Linq query expression code that should get exactly what you're looking for:
using System;
using System.Collections.Generic;
using System.Linq;
class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Traffic
{
public DateTime Date { get; set; }
public int PersonId { get; set; }
public int TrafficId { get; set; }
}
class TrafficType
{
public int Id { get; set; }
public string Description { get; set; }
}
class Program
{
static void Main(string[] args)
{
var persons = new List<Person>()
{
new Person()
{
Id = 1001,
FirstName = "David",
LastName = "Jones",
},
};
var trafficTypes = new List<TrafficType>()
{
new TrafficType()
{
Id = 456,
Description = "sample description",
},
};
var traffics = new List<Traffic>()
{
new Traffic()
{
PersonId = 1001,
TrafficId = 456,
Date = DateTime.Now,
},
};
var joinedData = from p in persons
from t in traffics
from tt in trafficTypes
where p.Id == t.PersonId
&& tt.Id == t.TrafficId
select new
{
PersonId = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
// Remove time component, if present
Date = t.Date.Date,
Description = tt.Description,
};
foreach (var item in joinedData)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}"
, item.PersonId
, item.FirstName
, item.LastName
, item.Date.ToShortDateString() // Don't print the time
, item.Description
);
}
}
}
The program output is:
1001 David Jones 7/19/2011 sample description
You can put them all in a class e.g. (Problem), then use a method for your output.
class Problem
{
public Problem()
{
}
public void Show()
{
// implement your output here
}
}
Or, if you are using Windows Forms app and interisting in Tables, you can use DataGridView control. For more information about it, visit http://msdn.microsoft.com/en-us/library/e0ywh3cz.aspx
Or, use DataGrid: http://www.codeproject.com/KB/grid/usingdatagrid.aspx

Categories