简体   繁体   English

实体框架-加载特定的外键数据

[英]Entity Framework - loading specific foreign key data

I have been trying to make it work but I don't know what I am missing here. 我一直在尝试使其工作,但我不知道我在这里缺少什么。

My models are: 我的模型是:

public class User
{
    public int id { get; set; }
    public string username { get; set; }

    public virtual List<UserMeta> usermeta { get; set; }

    public User()
    {
        this.usermeta = new List<UserMeta>();
    }

}

public class UserMeta
{
    public int id { get; set; }
    public string metakey { get; set; }
    public string value { get; set; }

    public virtual User user { get; set; }
}

I want to select metavalue for metakey = 'first_name' 我想为metakey ='first_name'选择元值

Currently this is what I have and its working: 目前,这是我所拥有的及其工作方式:

var user = db.Users.Include("UserMeta");

foreach (var item in user)
{
    Console.WriteLine(item.username);

    foreach (var item2 in item.usermeta)
    {
        // check item2.metakey for 'first_name'   
    }
}

But it won't work like this: 但这不会像这样工作:

var user = from u in db.Users
           select u;

foreach (var item in user)
{
    foreach (var item2 in item.usermeta)
    {
    }         
}

What is wrong in the second code snippet. 第二个代码段出了什么问题。 Also is there a better way of loading these? 还有一种更好的加载方式吗?

In the second code snippet you do not include the UserMeta table. 在第二个代码段中,您不包括UserMeta表。

Try this: 尝试这个:

var user = (from u in db.Users select u).Include("UserMeta");

I test this code in Console Application with EF 6.1.3 and no Problem (It is unlikely that the version of ef is problem), please test this code or compare with your code(your code is incomplete). 我在带有EF 6.1.3的控制台应用程序中测试了此代码,并且没有问题(ef的版本不太可能出现问题),请测试此代码或与您的代码进行比较(您的代码不完整)。

class Program
{
    static void Main(string[] args)
    {
        using (var db = new ApplicationContext())
        {
            var user = from u in db.Users select u;

            foreach (var item in user)
            {
                foreach (var item2 in item.usermeta)
                {
                    Console.WriteLine(string.Format($"{item2.metakey}:{item2.value}"));
                }
            }
        }

        Console.ReadKey();
    }
}

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

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