I've a model as described below:
public class Student
{
public int Id { get; set; }
public string Level { get; set; }
public string Subject { get; set; }
public string School { get; set; }
public int CityId { get; set; } //from City
}
public class City
{
public int Id { get; set; }
public string City { get; set; }
public int StateId { get; set; } //from State
}
public class State
{
public int Id { get; set; }
public string State { get; set; }
public int CountryId { get; set; } //from Country
}
public class Country
{
public int Id { get; set; }
public string Country { get; set; }
}
I wants to query the Student Entity and needs to include the Country (Only Country) to the student Model.
The Database structure is like as above, I cannot change the DB Table Structure.
But I can able to edit the EF Entities above. Ultimately I need the Student info with country as a Student Entity, So that I can draw jqGrid and sort them based on country too.
Well if you can't modify your entity classes to add the corresponding navigation properties, you can try this:
var query = from student in context.Students
join city in context.Cities on student.CityId equals city.Id
join state in context.States on city.StateId equals state.Id
join country in context.Countries on state.CountryId equals country.Id
select new {
StudentId=student.Id,
Level=student.Level,
...
Country=country.Country
};
Or maybe:
select new {Student=student, Country=country.Country};
If your tables are related, I suggest you include the navigation properties to your model:
public class Student
{
public int Id { get; set; }
//...
public int CityId { get; set; } //from City
public virtual City City{get;set;}
}
public class City
{
public int Id { get; set; }
//...
public int StateId { get; set; } //from State
public virtual City City{get;set;}
public virtual ICollection<Student> Students{get;set;}
}
public class State
{
public int Id { get; set; }
//...
public int CountryId { get; set; } //from Country
public virtual Country Country {get;set;}
public virtual ICollection<City> Cities{get;set;}
}
public class Country
{
public int Id { get; set; }
public string Country { get; set; }
public virtual ICollection<State> States{get;set;}
}
That is not going to affect your current DB schema. This way is more easy to reach to the country name using a student instance (as #SteveGreene show in his answer):
var countryName=student.City.State.Country.Country;
You can project that into an anonymous object or viewmodel:
var studentWithCountry = context.Student.Where(Id = myVar.Id)
.Select(s => new { Level = s.Level,
Subject = s.Subject,
...
Country = s.City.State.Country.Country });
Related
I m using Automapper in my project (.net 6). both Table have foreign key relationship. By using automapper mapping insert data, update data and get data from one entities is really flexible. but whenever I do join with query syntax I have to map data manually. I would like to know if there is any way to do this with AutoMapper, and how? so I can skip naming all fields or manual mapping. I used several technique with projecto Function can't find desire result.
My code.
Company Entities
public class Country
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[StringLength(256)]
public string CountryName { get; set; }
[StringLength(6)]
public string CountryAlias { get; set; }
[StringLength(10)]
public string TelephoneCode { get; set; }
}
City Entities
public class City
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[StringLength(256)]
public string CityName { get; set; }
[ForeignKey("CountryId")]
public Country Country { get; set; }
public int CountryId { get; set; }
}
CityDto
public class CityDto
{
public int CountryId { get; set; }
public int Id { get; set; }
public string CityName { get; set; }
public string CountryName { get; set; }
public int CreatedBy { get; set; }
}
API
public async Task<IEnumerable<CityDto>> GetAllCity()
{
return await (from country in _context.Countries
join city in _context.Cities on country.Id equals city.CountryId
orderby country.CountryName, city.CityName
select new CityDto
{
CountryId = city.CountryId,
CountryName = country.CountryName,
Id = city.Id,
CityName = city.CityName,
CreatedBy = city.CreatedBy,
})
.ToListAsync();
}
For my web app project, I have 2 models that are related to each other. Model Department is related to Model Employee. Each employee is assigned one department, while each department can have many employees. In the Departments view, I have an "Add new employee" option. When the add new employee button is clicked, a modal popup comes up which shows the Employees/Create view. My problem is I don't know how to link employee to department so that the employee automatically gets added to the department view next to the right department.
Right now, my Employee/Create view just gives the user a dropdown list of Departments to link the employee to. I want the employee to be automatically linked to the department when the "add employee" option is shown in the Departments view.
Here's the Department model:
public class Department
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string BuildingLocation { get; set; }
public string DirectLine { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
Here's the Employee model:
public class Employee
{
[Key]
public int EmployeeID { get; set; }
[ForeignKey("Department")]
public int DepartmentID { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeePosition { get; set; }
public string EmployeePhoneNo { get; set; }
public string EmployeeEmail { get; set; }
public virtual Department Department { get; set; }
}
I think you can create a EmployeeViewModel. For example:
public class Employee
{
public int EmployeeID { get; set; }
public int DepartmentID { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeePosition { get; set; }
public string EmployeePhoneNo { get; set; }
public string EmployeeEmail { get; set; }
public SelectListItem DepartmentList { get; set; }
}
When you click button add new employee, just set DepartmentId = DepartmentId that you selected. Or you can let the user changes Deparment.
You can create a ViewModel like this. Whenever you want to show employee details in the view then just map your data to this view model along with "DepartmentID" and "DepartmentName". To get "DepartmentName" you can join with department table and get department name.
public class EmployeeViewModel
{
public int EmployeeID { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeePosition { get; set; }
public string EmployeePhoneNo { get; set; }
public string EmployeeEmail { get; set; }
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public virtual Department Department { get; set; }
}
To Get Department Name you can join with Employe table like this. (Note that I've used EntityFramework here to retrieve data)
var employeeList = from e in dbContext.Employees
join d in dbContext.Departments on e.DepartmentID equals d.DepartmentID
select new EmployeeViewModel
{
EmployeeID = e.EmployeeID,
EmployeeFirstName = e.EmployeeFirstName,
EmployeePosition = e.EmployeePosition,
EmployeePhoneNo = e.EmployeePhoneNo,
EmployeeEmail = e.EmployeeEmail,
EmployeePhoneNo = e.Name,
DepartmentID = e.DepartmentID,
DepartmentName = d.DepartmentName
};
I have these entities:
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public Category Category { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
public class CustomerOrder
{
public int Id { get; set; }
public string Name { get; set; }
//Some other properties here...
public IEnumerable<Order> Orders { get; set; }
}
I'm using Linq to get a customer and his orders as follows:
var customers = dataContext.Set<Customer>();
return (from customer in customers
where customer.Id == id
select new CustomerOrder
{
Id = id,
Name = customer.Name,
Orders = customer.Orders
});
The above projects as expected. However, I need to retrieve the Category for each Order.
How can I do this by expanding the above Linq statement?
I have two classes that partake in a parent-child relationship. The parent class is Country, and the child class is City:
public partial class Country
{
public Country()
{
this.Cities = new List<City>();
}
public int Id { get; set; }
public string Name { get; set; }
public string AlphaCodeTwo { get; set; }
public string AlphaCodeThree { get; set; }
public Nullable<int> NumericCode { get; set; }
public string Capital { get; set; }
public string Nationality { get; set; }
public Nullable<decimal> CapitalArea { get; set; }
public Nullable<decimal> CapitalPopulation { get; set; }
public string Image { get; set; }
public virtual List<City> Cities { get; set; }
}
public partial class City
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public Nullable<int> NumericCode { get; set; }
public virtual Country Country { get; set; }
}
When I select a City object with the following LINQ query, the navigation property to the parent class is null:
private List<Country> _Country;
var City = _Country.SelectMany(c => c.Cities).OrderBy(ci => ci.Name).ToList();
I get all children, but no parent data.
If you're using Entity Framework, you can use .Include() to grab the navigation property data as you load the objects. Note that it tends to produce some pretty gnarly queries.
var city = (
from c in db.Cities.Include(c => c.Country)
where c.CountryId == CountryId
orderby c.Name
select c
).ToList();
I have two tables StudentPersonalInformation and EducationQualification
Here in MVC, I have create two model classes StudentPersonalInformation.cs and EducationQualification.cs, here I create the object of both classes in one wrapper class and that class Name is StudentInfo.cs
public class StudentPersonalInfo {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string StudentFirstName { get; set; }
public string StudentLastName { get; set; }
public int Age { get; set; }
public string BloodGroup { get; set; }
public string Address { get; set; }
}
public class EducationQualification {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Graduation { get; set; }
public int Grad_Marks_obtain { get; set; }
public string Grad_passing_year { get; set; }
public stringPost Graduation { get; set; }
public int PG_Marks_obtain { get; set; }
public string PG_passing_year { get; set; }
}
public class StudentInfo
{
public StudentPersonalInfo PersonalInfo { get; set; }
public EducationQualification EducationalQualification { get; set; }
}
This is the DBContext class:
public class StudentDbContext:DbContext
{
public DbSet<StudentPersonalInfo> StudentPersonalInfos { get; set; }
public DbSet<EducationQualification> EducationQualifications { get; set; }
}
And My Question is:
How to display the details by id of particular students from both tables in one view.
Please tell me how to do this….
You should make a ViewModel and in the controller action you should populate all the properties you want the view to have.
public class MyViewModelWithMultipleLists
{
public List<StudentPersonalInfo> Students{ get; set; }
public List<EducationQualification> Educations{ get; set; }
//etc
}
First you need to create a relationship between Student and Qualification by adding a navigation property to EducationQualification, assuming each qualification has 1 student.
public virtual Student Student {get; set;}
If a student can have more than one qualification, your StudentInfo model would be more likely to look like this:
public StudentPersonalInfo PersonalInfo { get; set; }
public List<EducationQualification> EducationalQualification { get; set; }
So then you you can query the db, and because you have created a relationship between student and qualification, your query will look something like:
var model= (from s in Student
where s.Id = id
select new StudentInfo
{
PersonalInfo = s,
EducationalQualification = s.EducationQualification.ToList()
}).FirstOrDefault()
You would pass the results:
return View(model);
to a strongly typed View:
#model StudentInfo
#Html.DisplayFor(x => x.PersonalInfo.StudentFirstName)
...etc