3

I have 2 tables Work_table and Employee_table.I want to display emp_id from Work_table and corresponding emp_name from Employee_table in the index view of Employee_table. my models are:

namespace MvcConQuery.Models
{
[Table("Work_Table")]
public class EnquiryModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int32 Enq_id { get; set; }
[Required]
[Display(Name="Name")]
public string CustomerName { get; set; }
[ReadOnly(true)]
public string Date
{
get
{
DateTime Date = DateTime.Now;
return Date.ToString("yyyy-MM-dd"); ;
}
set{}
}
[Required]
[Display(Name = "Region")]
public string Region { get; set; }
[Required]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone number format is not valid.")]
[Display(Name = "Phone number")]
public string Ph_No { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email_id")]
public string Email_id { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
[Required]
[Display(Name = "Query")]
public string Query { get; set; }
public string Referral { get; set; }
public string Feedback { get; set; }
public string Status { get; set; }
public Int32? Emp_id { get; set; }
public string FollowUpDate { get; set; }
public List<EmployeeModel> Employees { get; set; }
}}


namespace MvcConQuery.Models
{
[Table("Employee_Table")]
public class EmployeeModel
{

[Key,Column(Order=0)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
//[ForeignKey("EnquiryModel")]
public Int32 Emp_id { get; set; }
public string Emp_Name{ get; set; }
//[Key,Column(Order=1)]
public string Region { get; set; }
//[ForeignKey("Region")]
public string Emp_PhNo { get; set; }
public string Emp_Address { get; set; }
public List<EnquiryModel> Enquires { get; set; }


}

}

How to write controller? I stucked when writing the function in controller.

public ActionResult Index()
{
} 

Please suggest a solution. thanks in advance.

Regards

4
  • Where are you stuck? What was your attempt? Share your code and let us know. Commented Feb 26, 2014 at 10:13
  • I stucked when writing the function public ActionResult Index(){} in controller. Commented Feb 26, 2014 at 10:15
  • Is it possible to use another ViewModel class to join data from different tables Commented Feb 26, 2014 at 11:24
  • Yes, you need to create a ViewModel(with properties as per your need) to render data to the view. In the index action you need to join the two tables Work and Employee. As far as I can make out you should have a 1 -to - * relationship between Work and Employees. So in your index action you will need to fire a query that will join these two tables on EmployeeId and then bind the data to the corresponding properties in the ViewModel and then pass that to the view. I will try and put up something. Commented Feb 26, 2014 at 11:55

2 Answers 2

4

I was wrong earlier, I made out from your code that there is a many -to- many relationship between Employee and Work tables. For my convenience, I have used Job as the name for your Work table / model.

I hope that you want to display a list of EmployeeIds along with the corresponding EmployeeNames in the Index View. I have added an extra property called JobName to viewmodel, you can have other properties too.

For that matter, create a ViewModel EmployeeViewModel and bind the index view of your action result with an IEnumerable<EmployeeViewModel>. The definition for EmployeeViewModel can be something like -

    public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }

        public string EmployeeName  { get; set; }

        public string JobName { get; set; }

        //..Other memberVariables..
    }


Suppose these are your models -
Employee

        public class Employee
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int EmployeeId { get; set; }

            public string EmployeeName { get; set; }

            public string Address { get; set; }

            public virtual ICollection<Job> Jobs { get; set; }
        }

And WorkTable, renamed it as Job for my own convenience

    public class Job
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int JobId { get; set; }

        public string JobName { get; set; }

        public JobCategory JobCategory { get; set; }

        public int EmployeeId { get; set; }

        public virtual ICollection<Employee> Employees { get; set; }
    }

In your Index Action, you create a result set by joining the two tables, bind it to IEnumerable<EmployeeViewModel> and pass that as a model to the view. The View should receive a model of type IEnumerable<EmployeeViewModel> as I mentioned earlier,so you need to query your entities which should be something like -

    public ActionResult Index()
    {
        //..something like this..this is IQueryable..
        //...convert this to IEnumerable and send this as the model to ..
        //..the Index View as shown below..here you are querying your own tables, 
        //.. Employee and Job,and binding the result to the EmployeeViewModel which
        //.. is passed on to the Index view.
        IEnumerable<EmployeeViewModel> model=null;
        model = (from e in db.Employees
                    join j in db.Jobs on e.EmployeeId equals j.EmployeeId
                    select new EmployeeViewModel
                    {
                        EmployeeId = e.EmployeeId,
                        EmployeeName = e.EmployeeName,
                        JobName = j.JobName
                    });

        return View(model);
    }

Your index view should be something like -

@model IEnumerable<MyApp.Models.EmployeeViewModel>

@{
    ViewBag.Title = "Index";
}


<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.EmployeeId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmployeeName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.JobName)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.EmployeeId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EmployeeName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.JobName)
        </td>
    </tr>
}

</table>

In this above solution, I have made an attempt to generate a situation similar to yours and address your concerns. I hope this brings some sort of respite to your worries and helps you move ahead. Take this as a map and try follow the routes to find your own destination/solution. Btw, sorry for this delayed reply. Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

I got an error in controller: Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<MvcConQuery.Models.Employee viewModel>'. An explicit conversion exists (are you missing a cast?)
Yes thats what I commented out..its IQuertable,you need to convert that to IEnumerable.
@Nivya The main idea is you execute your logic there or call your methods from the repositories in the ActionResult.
Yes I convert it,Now it is working.Thank You very much.
What about accessing the an already defined SQL View? I'm not going to have direct read access to all tables. I just need to read a view, no updates. modelBuilder.Entity<DataSubmissionCycle>().ToTable("vw_DataSubmissionCycle");
0

This code has something missing select new EmployeeviewModel

model = (from e in db.Employees
                    join j in db.Jobs on e.EmployeeId equals j.EmployeeId
                    select new EmployeeViewModel
                    {
                        EmployeeId = e.EmployeeId,
                        EmployeeName = e.EmployeeName,
                        JobName = j.JobName
                    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.