[英]Return generic lists by Entity Framework join
I'm using Entity Framework and want to join 2 tables, then return it as a list.我正在使用 Entity Framework 并想连接 2 个表,然后将其作为列表返回。
But my method returns List<contact>
( contact
is a table in my DB) and I can't return it.但是我的方法返回
List<contact>
( contact
是我数据库中的一个表),我无法返回它。 Because of the new object, not like contact
, how I can't return my result?因为新的object,不像
contact
,怎么回不了结果?
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.您不能返回匿名类型列表,因为 GetAllContract 方法需要一个联系人类型列表。 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
创建一个新的 class ,它将被设置为方法返回类型
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
然后像这样更改您的方法返回类型和您的 linq 查询
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.