Seed Data with ICollection? - c#

I have a school project with a one to many relationship (Contact can have many Addresses). But I don't know how to seed it correctly.
In my Data models Contact has a virtual ICollection<Address> Addresses and the address object has the foreign key of ContactId.
So here is my seed data (code first) And i need to make it so when i type in the contacts last name in a search bar it will pull up all the info on that contact (address Info).
So how do i associate the info together in my seed data so when you search it pulls up what it is supposed to?
namespace Success.Data.Migrations
{
public class Seeder
{
public static void Seed(SuccessContext context,
bool seedContacts = true,
bool seedAddresses = true)
{
if (seedContacts) SeedContacts(context);
if (seedAddresses) SeedAddresses(context);
}
private static void SeedContacts(SuccessContext context)
{
context.Contacts.AddOrUpdate(l => l.LastName,
new Contact() { FullName = "Darth Vader", FirstName = "Darth", LastName = "Vader", },
new Contact() { FullName = "Luke Skywalker", FirstName = "Luke", LastName = "Skywalker", },
new Contact() { FullName = "Tony Stark", FirstName = "Tony", LastName = "Stark", },
new Contact() { FullName = "Ricky Bobby", FirstName = "Ricky", LastName = "Bobby", },
new Contact() { FullName = "Trix Rabbit", FirstName = "Trix", LastName = "Rabbit", });
context.SaveChanges();
}
private static void SeedAddresses(SuccessContext context)
{
context.Addresses.AddOrUpdate(h => h.HomeAddress,
new Address() { HomeAddress = "1300 DeathStar", BusinessAddress = "444 Imperial Fleet", PoBox = "PO Box 1335", ContactId = 1, },
new Address() { HomeAddress = "1997 Endor", BusinessAddress = "448 Rebel Fleet", PoBox = "PO Box 1339", ContactId = 2, },
new Address() { HomeAddress = "1224 Malibu Point", BusinessAddress = "657 Stark Industries", PoBox = "PO Box 1337", ContactId = 3, },
new Address() { HomeAddress = "9978 Fast LN.", BusinessAddress = "532 NASCAR Race Track", PoBox = "PO Box 1333", ContactId = 4, },
new Address() { HomeAddress = "9864 Cerial Box LN", BusinessAddress = "8432 Kellog Dr.", PoBox = "PO Box 1338", ContactId = 5, });
context.SaveChanges();
}
}
}

You could have another method that seeds both the contacts and address. You will need an extra if/else switch
if (seedContacts && seedAddresses)
{
SeedContactsAndAddress(context);
}
else
{
if (seedContacts) SeedContacts(context);
if (seedAddresses) SeedAddresses(context);
}
And the SeedContactsAndAddress Method would look like this:
private static void SeedContactsAndAddress(StoreContext context)
{
// Each Address, which I believe is a collection in this case, but there is only
// one, will have to be created and added to each contact.
var addressesForDarthVader = new List<Address>
{
new Address { HomeAddress = "1300 DeathStar", BusinessAddress = "444 Imperial Fleet", PoBox = "PO Box 1335" }
// Add more addresses for Darth Vader if you need to
};
// Rinse and repeat for the other contacts;
context.Contacts.AddOrUpdate(l => l.LastName,
new Contact() { FullName = "Darth Vader", FirstName = "Darth", LastName = "Vader", Addresses = addressesForDarthVader },
new Contact() { FullName = "Luke Skywalker", FirstName = "Luke", LastName = "Skywalker", },
new Contact() { FullName = "Tony Stark", FirstName = "Tony", LastName = "Stark", },
new Contact() { FullName = "Ricky Bobby", FirstName = "Ricky", LastName = "Bobby", },
new Contact() { FullName = "Trix Rabbit", FirstName = "Trix", LastName = "Rabbit", });
context.SaveChanges();
}

Related

IActionResult pass object and message in Ok

In .NET 6 API controller, I'm returning data with Ok IActionResult, below is my code, there I want to pass a string message along with return Ok(employee);
Is it possible if so, please suggest how to do it.
[Route("{Id}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Employee))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetEmployeeDetails(int Id)
{
var listEmployees = new List<Employee>()
{
new Employee(){ Id = 1001, Name = "Anurag", Age = 28, City = "Mumbai", Gender = "Male", Department = "IT" },
new Employee(){ Id = 1002, Name = "Pranaya", Age = 28, City = "Delhi", Gender = "Male", Department = "IT" },
new Employee(){ Id = 1003, Name = "Priyanka", Age = 27, City = "BBSR", Gender = "Female", Department = "HR"},
};
var employee = listEmployees.FirstOrDefault(emp => emp.Id == Id);
if (employee != null)
{
**return Ok(employee);**
}
else
{
return NotFound();
}
}
In order to return the message with the data as well, I would suggest creating a model class that allows returning multiple values.
For example, an ApiResponse class that support generic type.
public class ApiResponse<T>
{
public string Message { get; set; }
public T Data { get; set; }
}
And your controller action to return the value of ApiResponse<Employee> type for the status 200 scenario as below:
[Route("{Id}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ApiResponse<Employee>))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetEmployeeDetails(int Id)
{
var listEmployees = new List<Employee>()
{
new Employee(){ Id = 1001, Name = "Anurag", Age = 28, City = "Mumbai", Gender = "Male", Department = "IT" },
new Employee(){ Id = 1002, Name = "Pranaya", Age = 28, City = "Delhi", Gender = "Male", Department = "IT" },
new Employee(){ Id = 1003, Name = "Priyanka", Age = 27, City = "BBSR", Gender = "Female", Department = "HR"},
};
var employee = listEmployees.FirstOrDefault(emp => emp.Id == Id);
if (employee != null)
{
return Ok(new ApiResponse<Employee>
{
Message = "Assign your message here",
Data = employee
});
}
else
{
return NotFound();
}
}
Unfortunately don't think that is possible to do. The workaround could be that you add an extra field to the Employee object such as a string of description that gets returned as a whole.

How can I access obj from a list of student courses

I've created a list of courses that students are enrolled in. However, I can't figure out how to access the objects from the list in the Main. Below, I've tried to get the Student-Id and pull the information from there, but it isn't working. I'm new to coding please help
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace Jvstt_College
{
class Admin
{
##
## Dictionary<int, Student> studentList = new Dictionary<int, Student>();
Dictionary<int, Professor> professorList = new Dictionary<int, Professor>();
List<Course> courseList = new List<Course>();
Dictionary<int, Student> studentCourses = new Dictionary<int, Student>();
public Dictionary<int, Student> StudentList()
{
var Student1 = new Student() { FirstName = "Tom", LastName = " Jones", Password = "Test", EnrollmentId = 111111};
var Student2 = new Student() { FirstName = "Mark", LastName = " Thomas", Password = "Grace", EnrollmentId = 101203 };
var Student3 = new Student() { FirstName = "Jake", LastName = " Riley", Password = "SavedbyChrist1", EnrollmentId = 568903 };
var Student4 = new Student() { FirstName = "Olivia", LastName = " Beckam", Password = "GodisGood", EnrollmentId = 951357 };
var Student5 = new Student() { FirstName = "Myrai", LastName = " Bailey", Password = "ChildofGod", EnrollmentId = 741369 };
var Student6 = new Student() { FirstName = "Majea", LastName = " Bailey", Password = "CoastLand", EnrollmentId = 852146 };
studentList.Add(111111, Student1);
studentList.Add(101203, Student2);
studentList.Add(568903, Student3);
studentList.Add(951357, Student4);
studentList.Add(741369, Student5);
studentList.Add(852146, Student6);
return studentList;
}
public Dictionary<int, Professor> ProfessorList()
{
professorList.Add(654321, new Professor { FirstName = "Grace", LastName = "Riley", Password = "Gracey1983", EnrollmentId = 654321 });
enter code here professorList.Add(852963, new Professor { FirstName = "Liam", LastName = "Beckam", Password = "Password", EnrollmentId = `enter code here`852963 });
professorList.Add(359861, new Professor { FirstName = "Martha", LastName = "Hart", Password = "QwertYy00", EnrollmentId = 359861 });
professorList.Add(612832, new Professor { FirstName = "George", LastName = "Washington", Password = "Kid$nExtD00r", EnrollmentId = 612832 });
return professorList;
}
public List<Course> CourseList()
{
var Accounts = new Course() { CourseID = 101, CourseName = " Accounts " };
var Bio_Psychology = new Course() { CourseID = 102, CourseName = " Bio_Psychology " };
var Business = new Course() { CourseID = 103, CourseName = " Business " };
var Chemistry = new Course() { CourseID = 104, CourseName = " Chemistry " };
var CSWDCA = new Course() { CourseID = 105, CourseName = " Computer Science/Web Design/Cybersecurity Accounts" };
var Psychology = new Course() { CourseID = 106, CourseName = " Psychology " };
var Statistics = new Course() { CourseID = 107, CourseName = " Statistics " };
var Advance_Math = new Course() { CourseID = 108, CourseName = "Advance Math" };
courseList.Add(Accounts);
courseList.Add(Bio_Psychology);
courseList.Add(Business);
courseList.Add(Chemistry);
courseList.Add(CSWDCA);
courseList.Add(Psychology);
courseList.Add(Statistics);
courseList.Add(Advance_Math);
return courseList;
}
public Dictionary<int, Student> StudentEnrollments()
{
var Student1 = studentList[111111];
{
if(Student1.Courses == null)
{
Student1.Courses = new List<Course>();
Student1.Courses?.Add(courseList[0]);
Student1.Courses?.Add(courseList[2]);
Student1.Courses?.Add(courseList[4]);
}
}
var Student2 = studentList[101203];
{
if(Student2.Courses == null)
{
Student2.Courses = new List<Course>();
Student2.Courses?.Add(courseList[1]);
Student2.Courses?.Add(courseList[4]);
Student2.Courses?.Add(courseList[5]);
Student2.Courses?.Add(courseList[6]);
Student2.Courses?.Add(courseList[7]);
}
}
var Student3 = studentList[568903];
{
if (Student3.Courses == null)
{
Student3.Courses = new List<Course>();
Student3.Courses?.Add(courseList[1]);
Student3.Courses?.Add(courseList[4]);
}
}
var Student4 = studentList[951357];
{
if (Student4.Courses == null)
{
Student4.Courses = new List<Course>();
Student4.Courses?.Add(courseList[1]);
Student4.Courses?.Add(courseList[5]);
Student4.Courses?.Add(courseList[7]);
}
}
var Student5 = studentList[741369];
{
if (Student5.Courses == null)
{
Student5.Courses = new List<Course>();
Student5.Courses?.Add(courseList[0]);
Student5.Courses?.Add(courseList[2]);
Student5.Courses?.Add(courseList[3]);
Student5.Courses?.Add(courseList[6]);
Student5.Courses?.Add(courseList[7]);
}
}
var Student6 = studentList[852146];
{
if (Student6.Courses == null)
{
Student6.Courses = new List<Course>();
Student6.Courses?.Add(courseList[0]);
Student6.Courses?.Add(courseList[1]);
Student6.Courses?.Add(courseList[2]);
Student6.Courses?.Add(courseList[3]);
Student6.Courses?.Add(courseList[4]);
Student6.Courses?.Add(courseList[5]);
Student6.Courses?.Add(courseList[6]);
}
}
studentCourses.Add(111111,Student1);
studentCourses.Add(101203,Student2);
studentCourses.Add(568903,Student3);
studentCourses.Add(951357,Student4);
studentCourses.Add(741369,Student5);
studentCourses.Add(852146,Student6);
return studentCourses;
}
}
}
}
First, let's declare the Professor, Student and Course classes. Since Professor and Student have similar properties and since they both are persons, it makes sense to derive them both from an abstract Person class. An abstract class cannot be instantiated.
abstract class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public int EnrollmentId { get; set; }
}
class Professor : Person
{
}
class Student : Person
{
public List<Course> Courses { get; } = new List<Course>();
}
class Course
{
public int CourseID { get; set; }
public string CourseName { get; set; }
}
In class Student I created the Courses list as read-only property and initialized it with a property initializer. This saves you from having to do something like if (Student2.Courses == null) { Student2.Courses = new List<Course>(); ... } later.
You have several method initializing lists and dictionaries. Those should declare and create the collections they return. Otherwise, if the collections are declared in a surrounding scope, the return statement would not be required and the responsibilities would not be clear. Add also, a dictionary is not a list. Since these methods do rely on instance fields anymore, we make them static (and simplify them):
// In class Admin
private static Dictionary<int, Student> CreateStudents()
{
return new Dictionary<int, Student> {
{ 111111, new Student { FirstName = "Tom", LastName = " Jones", Password = "Test", EnrollmentId = 111111 } },
{ 101203, new Student { FirstName = "Mark", LastName = " Thomas", Password = "Grace", EnrollmentId = 101203 } },
{ 568903, new Student { FirstName = "Jake", LastName = " Riley", Password = "SavedbyChrist1", EnrollmentId = 568903 } },
{ 951357, new Student { FirstName = "Olivia", LastName = " Beckam", Password = "GodisGood", EnrollmentId = 951357 } },
{ 741369, new Student { FirstName = "Myrai", LastName = " Bailey", Password = "ChildofGod", EnrollmentId = 741369 } },
{ 852146, new Student { FirstName = "Majea", LastName = " Bailey", Password = "CoastLand", EnrollmentId = 852146 } }
};
}
private static Dictionary<int, Professor> CreateProfessors()
{
return new Dictionary<int, Professor> {
{ 654321, new Professor { FirstName = "Grace", LastName = "Riley", Password = "Gracey1983", EnrollmentId = 654321 } },
{ 852963, new Professor { FirstName = "Liam", LastName = "Beckam", Password = "Password", EnrollmentId = 852963 } },
{ 359861, new Professor { FirstName = "Martha", LastName = "Hart", Password = "QwertYy00", EnrollmentId = 359861 } },
{ 612832, new Professor { FirstName = "George", LastName = "Washington", Password = "Kid$nExtD00r", EnrollmentId = 612832 } }
};
}
private static List<Course> CreateCourses()
{
return new List<Course> {
new Course { CourseID = 101, CourseName = "Accounts" },
new Course { CourseID = 102, CourseName = "Bio_Psychology" },
new Course { CourseID = 103, CourseName = "Business" },
new Course { CourseID = 104, CourseName = "Chemistry" },
new Course { CourseID = 105, CourseName = "Computer Science/Web Design/Cybersecurity Accounts" },
new Course { CourseID = 106, CourseName = "Psychology" },
new Course { CourseID = 107, CourseName = "Statistics" },
new Course { CourseID = 108, CourseName = "Advance Math" }
};
}
Now, we can declare and initialize the collections like this:
class Admin
{
public readonly Dictionary<int, Student> students = CreateStudents();
public readonly Dictionary<int, Professor> professors = CreateProfessors();
public readonly List<Course> courses = CreateCourses();
...
}
I made them read-only. This only means that we cannot assign it another collection later. The collections themselves are still read/write.
We do not need another collection studentCourses, we can directly add the courses to the students in our existing students dictionary.
If we declare an instance method EnrollStudents in class Admin, then it can access the fields of this class.
public void EnrollStudents()
{
Student student = students[111111];
student.Courses.Add(courses[0]);
student.Courses.Add(courses[2]);
student.Courses.Add(courses[4]);
student = students[101203]; // It is okay to reuse the student variable
student.Courses.Add(courses[1]);
student.Courses.Add(courses[4]);
student.Courses.Add(courses[5]);
student.Courses.Add(courses[6]);
student.Courses.Add(courses[7]);
student = students[568903];
student.Courses.Add(courses[1]);
student.Courses.Add(courses[4]);
student = students[951357];
student.Courses.Add(courses[1]);
student.Courses.Add(courses[5]);
student.Courses.Add(courses[7]);
student = students[741369];
student.Courses.Add(courses[0]);
student.Courses.Add(courses[2]);
student.Courses.Add(courses[3]);
student.Courses.Add(courses[6]);
student.Courses.Add(courses[7]);
student = students[852146];
student.Courses.Add(courses[0]);
student.Courses.Add(courses[1]);
student.Courses.Add(courses[2]);
student.Courses.Add(courses[3]);
student.Courses.Add(courses[4]);
student.Courses.Add(courses[5]);
student.Courses.Add(courses[6]);
}
Note that we do not have to return anything. Since classes are reference types, all the students in the original students dictionary have now been updated with courses. Of course we must call this method somewhere (probably in Main).
But we can simplify this method with a new helper method, because we have a lot of repetitions we can avoid:
private void AddStudentCourses(Student student, params int[] courseIndexes)
{
foreach (int index in courseIndexes) {
student.Courses.Add(courses[index]);
}
}
public void EnrollStudents()
{
AddStudentCourses(students[111111], 0, 2, 4);
AddStudentCourses(students[101203], 1, 4, 5, 6, 7);
AddStudentCourses(students[568903], 1, 4);
AddStudentCourses(students[951357], 1, 5, 7);
AddStudentCourses(students[741369], 0, 2, 3, 6, 7);
AddStudentCourses(students[852146], 0, 1, 2, 3, 4, 5, 6);
}
Test:
var admin = new Admin();
admin.EnrollStudents();
var orderedStudents = admin.students.Values
.OrderBy(s => s.LastName)
.ThenBy(s => s.FirstName);
foreach (var student in orderedStudents) {
Console.WriteLine($"{student.LastName} {student.FirstName} ({student.EnrollmentId})");
IOrderedEnumerable<Course> orderedCourses = student.Courses.OrderBy(c => c.CourseName);
foreach (var course in orderedCourses) {
Console.WriteLine($" {course.CourseName} ({course.CourseID})");
}
Console.WriteLine();
}
Prints
Bailey Majea (852146)
Accounts (101)
Bio_Psychology (102)
Business (103)
Chemistry (104)
Computer Science/Web Design/Cybersecurity Accounts (105)
Psychology (106)
Statistics (107)
Bailey Myrai (741369)
Accounts (101)
Advance Math (108)
Business (103)
Chemistry (104)
Statistics (107)
Beckam Olivia (951357)
Advance Math (108)
Bio_Psychology (102)
Psychology (106)
Jones Tom (111111)
Accounts (101)
Business (103)
Computer Science/Web Design/Cybersecurity Accounts (105)
Riley Jake (568903)
Bio_Psychology (102)
Computer Science/Web Design/Cybersecurity Accounts (105)
Thomas Mark (101203)
Advance Math (108)
Bio_Psychology (102)
Computer Science/Web Design/Cybersecurity Accounts (105)
Psychology (106)
Statistics (107)

EntityValidationError in EntityFramework Code first migration

I am getting this error:
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
In visual studio. There are several posts on here about it however all of them seem to be running a "seed" method somewhere in the application flow.
In my case I am trying to seed the database in the Configuration of the migrations. If that is ill advised please let me know.
There is now way to catch exceptions or break in any way when Update-Database is run. How can I view the details of the error message?
protected override void Seed(AppContext context)
{
User[] Users = new User[]
{
new User()
{
Id = new Guid().ToString(),
FirstMidName = "Arianne",
LastName = "Brower",
BirthDate = DateTime.Now,
UserType = UserType.Member,
Gender = Gender.Female,
ExerPoints = 500,
Contact = new Contact()
{
Address = "#2 HomeLand Rd, Central Town",
PhoneNumber = "1-868-555-0912",
}
},
new User()
{
Id = new Guid().ToString(),
FirstMidName = "Melaino",
LastName = "Cruaino",
BirthDate = DateTime.Now,
UserType = UserType.Instructor,
Gender = Gender.Male,
ExerPoints = 1520,
Contact = new Contact()
{
Id = new Guid().ToString(),
Address = "#2 HomeLand Rd, Central Town",
PhoneNumber = "1-868-555-0912",
}
},
new User()
{
Id = new Guid().ToString(),
FirstMidName = "Darion",
LastName = "Carpenter",
BirthDate = DateTime.Now,
UserType = UserType.Member,
Gender = Gender.Male,
ExerPoints = 2960,
Contact = new Contact()
{
Id = new Guid().ToString(),
Address = "#2 HomeLand Rd, Central Town",
PhoneNumber = "1-868-555-0912",
}
},
new User()
{
Id = new Guid().ToString(),
FirstMidName = "Alexa",
LastName = "Bringer",
BirthDate = DateTime.Now,
UserType = UserType.Member,
Gender = Gender.Female,
ExerPoints = 3900,
Contact = new Contact()
{
Id = new Guid().ToString(),
Address = "#2 HomeLand Rd, Central Town",
PhoneNumber = "1-868-555-0912",
}
},
new User()
{
Id = new Guid().ToString(),
FirstMidName = "Alexa",
LastName = "Bringer",
BirthDate = DateTime.Now,
UserType = UserType.Organizer,
Gender = Gender.Female,
ExerPoints = 12000,
Contact = new Contact()
{
Id = new Guid().ToString(),
Address = "#2 HomeLand Rd, Central Town",
PhoneNumber = "1-868-555-0912",
}
}
};
context.Users.AddOrUpdate(Users);
Club[] Clubs = new Club[]
{
new Club()
{
Id = new Guid().ToString(),
Name = "Road Runners",
ContactInfo = new Contact() {
Id = new Guid().ToString(),
Address = "Lakanda Rd, POS",
PhoneNumber = "1-868-555-0011",
Website = "www.roadrunnerstt.tt"
},
PointsDistributed = 15950,
PointsEarned = 25500
},
new Club()
{
Id = new Guid().ToString(),
Name = "Weightornators",
ContactInfo = new Contact() {
Id = new Guid().ToString(),
Address = "Lakanda Rd, POS",
PhoneNumber = "1-868-555-0011",
Website = "www.weightornators.tt"
},
PointsDistributed = 250000,
PointsEarned = 325000
},
};
context.Clubs.AddOrUpdate(
Clubs
);
}
}

C# linq query All method

Have a collection
List<<KeyValuePair<string, Person>>
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int MealType { get; set; }
}
patientEffort.Add("1", new Person() { FirstName = "Raja", LastName = "Ram", MealType = 2 });
patientEffort.Add("2", new Person() { FirstName = "Vijay", LastName = "Anthony", MealType = 1 });
patientEffort.Add("2", new Person() { FirstName = "Vijay", LastName = "Anthony", MealType = 2 });
patientEffort.Add("2", new Person() { FirstName = "Vijay", LastName = "Anthony", MealType = 3 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 1 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 2 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 3 });
patientEffort.Add("3", new Person() { FirstName = "Dr", LastName = "APJ", MealType = 4 });
List<int> _listMealType = new List<int>();
If _listMealType= [2] passed then Result will be
{Key: "1", FirstName = "Raja", LastName = "Ram"}
{Key: "2", FirstName = "Vijay", LastName = "Anthony"}
{Key: "3", FirstName = "Dr", LastName = "APJ"}
If _listMealType= [1,2,3] passed then Result will be
{Key: 2, FirstName = "Vijay", LastName = "Anthony"}
{Key: 3, FirstName = "Dr", LastName = "APJ"}
If _listMealType= [1,2,3,4] passed then Result will be
{Key: "3", FirstName = "Dr", LastName = "APJ"} only
Key may be string or int that doesn't matter. May I have linq query for this scenario. I have used All method is linq but not worked.
var query = patientEffort.Where(d => _listMealType.All(x => x == d.Value.MealType)).Select(d => d.Key);
Could you please help me in solving the query issue as soon as possible.
I hope it helps:
var patients = patientEffort.GroupBy(x => x.Value.FirstName);
var result = (from patient in patients let res = patient.Select(note => note.Value.MealType).ToList() where _listMealType.Intersect(res).Count() == _listMealType.Count select patient.First()).ToList();
Here is variant without linq using:
var patients = patientEffort.GroupBy(x => x.Value.FirstName); // group patients by name
foreach (var patient in patients)
{
var res = new List<int>();
foreach (var note in patient) // collect all meal types of current patient
res.Add(note.Value.MealType);
if (_listMealType.Intersect(res).Count() == _listMealType.Count) // if intersection count equal to source meal list - it's our patient.
result.Add(patient.First()); // add information about patient. because we need only name - we can use first record in list.
}

Flatten LINQ Collection

I have had a look at this Flatten LINQ collection object with nested object collections but it doesn't quite do it for me.
I know there is a lot of code in this post but it's mostly just data to give you the idea of what I'm looking at developing.
if you look at the classes below, I am trying to come up with a way to flatten the result of a search against the file.
So i need to end up with a single flattened record which looks like (the pipes are there to show delimination of a field only)
fileId | FileContact1FirstName | FileContact1LastName | FileContact2FirstName etc | FileClient1FirstName | FileClient1LastName | FileClient1IsNominee | FileClient1IsPrimary | FileClient2FirstName etc....
Any idea on how I can do this without looping through each Contact and Client?
I have these classes of sorts in my edmx;
class File
{
public int fileId { get; set; }
public List<FileContact> fileContacts { get; set; }
public List<FileClient> fileClients { get; set; }
}
class FileContact
{
public Contact contact { get; set; }
}
class FileClient
{
public Contact contact { get; set; }
public bool IsNominee { get; set; }
public bool IsPrimary { get; set; }
}
class Contact
{
public int id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}
And this this as the data simply for testing.
static void FillData()
{
thisFile = new File { fileId = 1, fileContacts = new List<FileContact>(), fileClients = new List<FileClient>() };
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Andrew", lastName = "Albino" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Bob", lastName = "Bush" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Cathy", lastName = "Conti" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Drew", lastName = "Dram" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Edward", lastName = "Eliston" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Frank", lastName = "Fashion" } });
thisFile.fileContacts.Add(new FileContact { contact = new Contact { id = 1, firstName = "Graham", lastName = "Grape" } });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Harry", lastName = "Who didn't" }, IsNominee = true, IsPrimary = false });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Indigo", lastName = "Ignacio" }, IsNominee = false, IsPrimary = false });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Julie", lastName = "Juniper" }, IsNominee = false, IsPrimary = false });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Kelly", lastName = "Keilor" }, IsNominee = false, IsPrimary = false });
thisFile.fileClients.Add(new FileClient { contact = new Contact { id = 1, firstName = "Liam", lastName = "Loser" }, IsNominee = false, IsPrimary = true });
}
}
This will get you an IEnumerable<string> that contains the properties in the order you specified:
var flattened = new string[] { thisFile.fileId.ToString() }
.Concat(
thisFile.fileContacts
.SelectMany(fc => new string[]
{
fc.contact.firstName,
fc.contact.lastName
}))
.Concat(
thisFile.fileClients
.SelectMany(fc => new string[]
{
fc.contact.firstName,
fc.contact.lastName,
fc.IsNominee.ToString(),
fc.IsPrimary.ToString()
}));
Example: http://ideone.com/Mvc7M
Have a look at SelectMany.

Categories

Resources