实体框架不从相关的表中获取数据 [英] Entity Framework don't take data from table which is related

查看:57
本文介绍了实体框架不从相关的表中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我对EntityFramework有问题。我有一对多的关系。

Hello I have problem with EntityFramework. I have relation one to many.

public class Question
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public string Description { get; set; }

    [Required]
    public DateTime AddDate { get; set; }

    [Required]
    public string Author { get; set; }

    [Required]
    public bool IsApproved { get; set; } = false;

    public ICollection<Answer> Answers { get; set; }
}

和次类:

public class Answer
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Text { get; set; }
    [Required]
    public string FileName { get; set; }

    public Question Question { get; set; }
}

我们如何看待我在这些表之间设置的关系。
很不幸,当我简单选择

How we can see I set relations between these tables. Unfortunatelly when I do simple select

_context.Question.OrderByDescending(x => x.AddDate).Take(10)

答案对象始终为null。
我检查了MSSQL中的键。问题表没有任何答案的答案,但答案有问题的答案。

Answers object is always null. I checked Keys in MSSQL. Question table don't have any FK to Answers, but Answers have FK to Question.

有人可以为我解释我做错了什么吗?为什么不创建FK?
我尝试使用虚拟类型,但无济于事。

Can anybody explain for me what I am doing wrong? Why FK is not created? I was trying virtual type but it is not helping.

推荐答案

Question 表,因为FK的shadow属性仅在Answer对象的关系的很多侧创建。

There shouldn't be any FK in the Question table, because the shadow property for the FK is created only on the 'many' side of the relationship in the Answer object.

基本上,您有两个选项


  1. 显式加载答案:

  1. Explicitly load the Answers:

var questions = _context.Question.OrderByDescending(x => x.AddDate).Take(10);
_contest.Answer.Where(x => questions.Select(q => q.Id)
                           .Contains(EF.Property<int>(x, "QuestionId"))).Load();


在这有点令人费解的陈述之后,所有答案将填充适当的对象。请注意FK使用自动创建的shadow属性。 此处。

After this a bit convoluted statement all Answers will be populated with the appropriate objects. Note the use of the autocreated shadow property for FK. More on the naming conventions here.


  1. 更容易渴望加载集合:

  1. Far more easily would be to eagerly load the collections:

_context.Question.OrderByDescending(x => x.AddDate).Take(10).Include(x => x.Answers);


这效率更高,可读性强

另外,值得注意的是, 目前,EF Core不支持延迟加载

Also, it's worth noting that EF Core does not support lazy loading as of this moment.

这篇关于实体框架不从相关的表中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆