简体   繁体   English

Linq select为两个嵌套对象之一返回null

[英]Linq select returns null for one of two nested objects

I have a Linq select statement that is supposed to return objects that have 2 nested objects. 我有一个Linq select语句,它应该返回有2个嵌套对象的对象。 The problem is, one of the nested objects is returning null while the other is working as intended. 问题是,其中一个嵌套对象返回null而另一个正在按预期工作。

Here is the object being queried: 这是被查询的对象:

public class CharInvCard
{
    public int ID { get; set; }
    public Character Character { get; set; }
    public Card Card { get; set; }
    public bool inDeck { get; set; }
    public bool inHand { get; set; }
    public bool inDiscard { get; set; }
}

Here is my Linq query: 这是我的Linq查询:

IQueryable<CharInvCard> CardsInHand = from x in db.CharInvCards
                               where x.Character.ID == character.ID && x.inHand == true
                               select x;

After getting the results of this query I do a foreach loop that starts like this: 获得此查询的结果后,我执行一个foreach循环,如下所示:

foreach (CharInvCard deckCardRec in CardsInHand)

While debugging, if I inspect the contents of deckCardRec I see that it has all its properties for ID, inHand, inDeck, inDiscard and even a nested Character object (and its properties) but Card is always null. 在调试时,如果我检查deckCardRec的内容,我看到它具有ID,inHand,inDeck,inDiscard甚至嵌套的Character对象(及其属性)的所有属性,但Card始终为null。

I've checked and double checked that the Card_Id column in my database is populated with the proper ID corresponding to the Card table. 我已经检查并仔细检查了我的数据库中的Card_Id列是否填充了与Card表对应的正确ID。

What is causing the Card nested object is returned as null while the Character nested object to be returned properly? 什么导致Card嵌套对象返回null,而Character嵌套对象要正确返回?

You are referencing Character in your linq query, so it is included. 您在linq查询中引用了Character ,因此它包含在内。 You are not referencing Card though. 你没有引用Card Try eager loading Cards as below: 尝试急切加载Cards如下:

IQueryable<CharInvCard> CardsInHand = from x in db.CharInvCards.Include("Cards")
                               where x.Character.ID == character.ID && x.inHand == true
                               select x;

I have assumed your navigational property is named "Cards" above. 我假设您的导航属性在上面被命名为“卡片”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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