简体   繁体   中英

Return generic lists by Entity Framework join

I'm using Entity Framework and want to join 2 tables, then return it as a list.

But my method returns List<contact> ( contact is a table in my DB) and I can't return it. Because of the new object, not like contact , how I can't return my result?

This is my code

public List<contact> GetAllContact()
{
     return db.contact.Where(c => c.deleted_at == null)
                      .Join(db.contact_image, contact => contact.id, image => image.contact_id, 
                            (contact, image) => new { 
                                                        contact.id,
                                                        contact.first_name,
                                                        contact.last_name,
                                                        contact.mobile,
                                                        contact.email,
                                                        contact.brithday,
                                                        contact.brithday_fa,
                                                        contact.created_at,
                                                        contact.updated_at,
                                                        contact.deleted_at,
                                                        image.image
                                                    }).ToList();
}

You cannot return a list of anonymous types as the GetAllContract method is expecting a List of contact types. If you want to return something other than a contact type you have to explicitly define it. Create a new class which will be set as the method return type

public class Contact_BO {
    public int ID {get;set;}
    public string First_Name { get; set; }
    public string Last_Name{ get; set; }
    public string Mobile { get; set; }
}

Off course you can add any more properties you wish. Then change your method return type and your linq query like this

public List<Contact_BO> GetAllContact()
{
     return db.contact.Where(c => c.deleted_at == null)
                      .Join(db.contact_image, contact => contact.id, image => image.contact_id, 
                            (contact, image) => 
                                new Contact_BO { 
                                        ID = contact.id,
                                        First_Name = contact.first_name,
                                        Last_Name.last_name,
                                        Mobile = contact.mobile,
                                    }).ToList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM