0

We have two models vw_fleet and fleet_contact generated by the entity framework. We are using views to retrieve data and we can't define the relationship between those models but when we retrieve data for fleet_contact we need fleet information as well.

public partial class vw_fleet
            {
                public int account_id { get; set; }
                public int fleet_id { get; set; }
                public string fleet_name { get; set; }
            }



 public partial class fleet_contact
            {
                public int id { get; set; }
                public int fleet_id { get; set; }
                public string contact { get; set; }
            }

We have added a property(Fleet) to fleet_contact

     public partial class fleet_contact 
          {
               public vw_fleet Fleet { get; set; }
          }

One way to do that is by using join.

using (var context = new EFEntities())
            {
return context.fleet_contact.Join(context.vw_fleet, fc => fc.fleet_id, f => f.fleet_id, (fc, f) => new FleetContactModel()
                {
                    fleet_id = fc.fleet_id,
                    Fleet = f,
                    contact = fc.contact,
                    id = fc.id,
                }
                ).ToList();
}

Is there any way to achieve the above solution.

Gokul
  • 21
  • 5
  • See msdn left outer join : https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b – jdweng Oct 15 '18 at 17:26
  • What is wrong with the code you provided? – NetMage Oct 15 '18 at 23:25
  • @NetMage, There is nothing wrong in the code that I have provided but I am looking a way to build a relationship between fleet_contact and vw_fleet using FluentAPI or any other techniques. That way I can avoid doing join. – Gokul Oct 16 '18 at 20:41
  • Why can't you define a relationship and navigation properties? (Which does a join behind the scenes) – NetMage Oct 16 '18 at 21:29
  • @NetMage, Since it's a view we can't define the relationship at the database level. I don't know a good way to define those relationships at the Entity Framework level. If there is a way to define it that would be great that's what I am looking for. If that relationship is established then all I need to do would be `return context.fleet_contact;` which would reduce manual mapping. But I don't know how to do that. Let me know if you have a good way to do it. – Gokul Oct 17 '18 at 21:19
  • FYI, We are doing Database first approach. So, entities and OnModelCreating class will get updated – Gokul Oct 17 '18 at 21:31
  • [This answer](https://stackoverflow.com/a/12483834/2557128) implies you do it in the model designer? – NetMage Oct 17 '18 at 21:53

0 Answers0