简体   繁体   English

实体框架6-上下文返回的列表的某些对象具有空属性

[英]Entity framework 6 - Some objects of the list returned by context have an empty property

I am retrieving a list of entities like this : 我正在检索这样的实体列表:

var traductions = from t in context.Traductions
                        where t.User.ID == user.ID
                        && (DateTime.Now < t.EndDate)
                        select t;

var list = traductions.ToList();

Here is the model : 这是模型:

Here is the first class :

    public class Original
    {
    public int ID { get; set; }
    public string Name { get; private set; }
    public Traduction Traduction { get; private set; }
    }

And here is the second class : 这是第二堂课:

   public class Traduction
   { 
    public int ID { get; set; }
    public Original Original { get; private set; }
    public string Content { get; private set; }
   }

I get 4 entities - that's good - however one of the properties of some of my retrieved objects is null - Original. 我得到4个实体-很好-但是某些检索到的对象的属性之一为null-原始。 In 3 of the 4 object the Original property is null, but this property is correctly populated in the 4th. 在4个对象中的3个中,Original属性为null,但在第4个中正确填充了此属性。 I have checked in the Database directly and the Primary Keys / FK are consistent. 我已经直接在数据库中签入,并且主键/ FK一致。

What do you think about it? 你怎么看待这件事? I don't understand because normally if there is a problem this property should be null for all the retrieved objects, but here the property is correctly populated for one of the objects. 我不明白,因为通常如果有问题,对于所有检索到的对象,此属性都应该为null,但是在这里,正确地为其中一个对象填充了该属性。

Thanks 谢谢

My first thought is you might have a circular reference. 我的第一个想法是您可能有一个循环参考。 Is it possible to have a Traduction, that contains an Original that contains the first Traduction? 是否可以有一个Traduction,其中包含包含第一个Traduction的原件? If you do that could be what you're seeing. 如果您这样做,那可能就是您所看到的。 You'll definitely have problems if/when you try to serialize things. 如果/当您尝试序列化事物时,肯定会遇到问题。

The following won't help a circular reference, but could be why the data is not loading as you'd expect. 以下内容无助于循环引用,但可能就是为什么数据未按预期加载的原因。

You could try using lazy loading. 您可以尝试使用延迟加载。 To do that you'll use the 'virtual' keyword in your classes like: 为此,您将在类中使用“虚拟”关键字,例如:

public class Original
{
    public int ID { get; set; }
    public string Name { get; private set; }
    public virtual Traduction Traduction { get; private set; }
}

public class Traduction
{ 
    public int ID { get; set; }
    public virtual Original Original { get; private set; }
    public string Content { get; private set; }
}

Or you can specifically include the objects in your query: 或者,您可以在查询中专门包含对象:

var traductions = from t in context.Traductions.Include("Original")
                  where t.User.ID == user.ID
                  && (DateTime.Now < t.EndDate)
                  select t;

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

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