[英]How to join two entity objects together?
我环顾四周以寻求答案,发现的内容与我正在执行的操作类似,但并没有完全正确。 当它们是列表时,我可以加入两个实体,但当它们是单个对象时,则不能。 我不确定这是否有意义
这里我有两个实体对象
Location location = VIPEF.Locations
.Where(w => w.LocationID == id).FirstOrDefault<Location>();
Contact contact = VIPEF.Contacts
.Where(w => w.ContactID == location.ContactID).FirstOrDefault<Contact>();
但是当我去写一个查询时:
var query = from a in location
join b in contact on a <-- Thats where I get a problem
一旦我加入了两者,就无法从位置获取ID,而我得到的唯一选择是a.equals
而不是我认为应该获取的a.LocationID
。
我在这里做错了什么?
您不需要Linq将两个对象连接在一起,只需要组成一个新对象。 使用对象初始化程序语法非常简单:
var thing = new Thing //<-- Your class that has the combined properties you need
{
LocationID = location.LocationID,
LocationName = location.Name,
ContactName = contact.Name,
ContactAddress = contact.Address,
//etc...
};
或者,您可以一次完成所有操作,而不是2个查询,然后进行合成:
var things = from l in VIPEF.Locations
join c in VIPEF.Contacts on l.ContactID equals c.ContactID
where l.LocationID == id
select new Thing
{
LocationID = location.LocationID,
LocationName = location.Name,
ContactName = contact.Name,
ContactAddress = contact.Address,
//etc...
};
这将为您提供一个IEnumerable<Thing>
,尽管它可能只有一个条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.