Home > front end >  combing two models and only retrieving a.firstname, a.lastname, b.name and returning as list to popu
combing two models and only retrieving a.firstname, a.lastname, b.name and returning as list to popu

Time:06-28

I have a UserTbl and a CongregationTbl and I am trying to combine them so that I can retrieve a.FirstName, a.LastName and b.Name.

UserTbl

| C_ID | FirstName | LastName |
 ------ ----------- ---------- 
   1       Jim         Jones
   2      Frank        Snow
   1      Alice        Cruz
   2      Sarah        Lee 

CongregationTbl

|  ID  |   Name    | 
 ------ ----------- 
   1      Bellham        
   2     Fortworth 

What I want to do return a list and populate that into a view

Created view

    | Name   | FirstName | LastName |
     -------- ----------- ---------- 
     Bellham     Jim         Jones
    Fortworth   Frank        Snow
     Bellham    Alice        Cruz
    Fortwroth   Sarah        Lee 

This is what I have so far. It returns data, but I cannot get it into my list.

using (Model1 dc = new Model1())
{
    var id = (from b in dc.CongregationTbls select b);
    var list = from i in dc.UserTbl 
               where i.AccountConfirmed == false 
               select new 
                      { id.FirstOrDefault().Name, i.FirstName, i.LastName };

    MergeModel MyModel = new MergeModel();
    MyModel.PendingUsers = list.ToList();
    return View(myModel);
}

CodePudding user response:

You should model your merged one like this. It's like making a custom model that allocates the first two models's important fields:

public class MergedModel{
     public string congregation {get;set;}
     public string firstname {get;set;}
     public string lastname {get;set;}
}

Then fill that model with the two models' data like this.

var merged = from user1 in UserTbl
                     join congregation1 in CongregationTbl on user1.C_ID equals congregation1.ID
                     select new MergedModel {congregation = congregation1.Name, firstname = user1.FirstName, lastname = user1.LastName };

Also, please note that var merged will converted as IEnumerable<MergedModel>. If you use the list as a return to your view to be called as @model IEnumerable<yourproject.Models.MergedModel> then it should work. Otherwise you can just reassign var merged like so:

List<MergedModel> merged2 = merged.ToList();

This is how I do it. I hope it helps you in any way.

  • Related