[英]Entity Framework join statement in a function
I'm trying to create a function to grab a List<>() of type "tableContact" which is an entity (sort of like when you do a simple select statement: query.ToList();) 我正在尝试创建一个函数来获取类型为“ tableContact”的List <>(),它是一个实体(类似于执行简单的select语句时的形式:query.ToList();)
But this is becoming frustrating because I kept getting "null object reference" errors. 但是,这变得令人沮丧,因为我一直收到“空对象引用”错误。 For some reason "join" statement doesn't work, so I tried an alternate linq statement.
由于某种原因,“ join”语句不起作用,因此我尝试了另一种linq语句。
I have an Object2Contacts table that I want to LEFT JOIN and I'm looking up my Object and trying to see all the contacts for this Object. 我有一个想保留联接的Object2Contacts表,我在查找我的对象并试图查看该对象的所有联系人。 I also can't figure out how to change an "anonymous type" back into an entity table.
我也想不出如何将“匿名类型”改回实体表。
Also not every object has contacts, so sometimes null List<> should be returned. 同样,并非每个对象都有联系人,因此有时应返回null List <>。
public List<tableContact> getContactsForObject(int oid)
{
if (oid > 0)
{
var query = (from s in entities.tableContacts
from o in entities.tableObject2Contacts
where s.contact_id == o.contact_id
where o.object_id == oid
select new { s });
if (query != null)
{
IEnumerable<tableContact> e = (IEnumerable<tableContact>)query.ToList();
return (List<tableContact>)e;
}
}
return new List<tableContact>();
}
I want to then loop through the object returned... eg: 然后,我想遍历返回的对象...例如:
foreach ( tableContact c in MyList){
WriteLine(c.Name);
}
EDIT I also tried: 编辑我也尝试过:
List<tableContacts> contacts = (from s in entities.tableContacts
join o in entities.tableObject2Contacts
on s.contact_id equals o.contact_id
where o.object_id == oid
select s).ToList();
Then I can't convert it back into a List and still "null reference". 然后,我无法将其转换回列表,并且仍然是“空引用”。
EDIT 2 Yes the query I am running may definitely bring in an "empty" list. 编辑2是的,我正在运行的查询肯定会带来一个“空”列表。 I don't mind empty lists, but it shouldn't give "object null reference."
我不介意空列表,但不应给出“对象空引用”。
I would write the join statement a little bit different: 我写的join语句有点不同:
var query = (from s in entities.tableContacts
join o in entities.tableObject2Contacts
on new { ContactID = s.contact_id, ObjectID = oid }
equals new { ContactID = o.contact_id, ObjectID = o.objectID }
into oTemp
from o in oTemp.DefaultIfEmpty()
select new { s });
This would be a proper left-join using linq. 这将是使用linq的正确左连接。 Maybe your NullReferenceException is caused by a wrong join or something.
也许您的NullReferenceException是由错误的连接或其他原因引起的。
Nevermind, The "I also tried this" is actually correct code, but for some reason I hadn't established my entities properly so that was returning null. 没关系,“我也尝试过这个”实际上是正确的代码,但是由于某种原因,我没有正确建立我的实体,因此返回null。
Although I'm still super confused about "anonymoustypes" I wouldn't know how to make a function that returns "anonymoustype". 尽管我仍然对“ anonymoustypes”感到非常困惑,但我不知道如何制作一个返回“ anonymoustype”的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.