简体   繁体   English

如何加载EF类及其关系类

[英]How do load EF class and it's relational classes

I have two tables: 我有两个表:

MY_TABLE
ID   CODE  VERSION  DESCRIPTION
1    AAA   1        A Test

MY_CHILD_TABLE
ID   CODE  VERSION  COLOR
1    AAA   1        Blue

Both are included in my EF model and there is a navigation property setup on both tables. 两者都包含在我的EF模型中,并且两个表上都有一个导航属性设置。

Now I have the following class to get the data: 现在,我有以下课程来获取数据:

public static MyData GetMyData(string Code, string version)
{
    using (var context = new Entities())
    {
        return context.MY_TABLE.Where(x => x.MY_CODE == Code && x.MY_VERSION == version).FirstOrDefault();
    }
} 

This is fine if I want just the data for MY_TABLE. 如果我只想要MY_TABLE的数据,那就很好。 However I now have a scenario where I want both MY_TABLE and MY_CHILD_TABLE data returned. 但是,现在我需要同时返回MY_TABLE和MY_CHILD_TABLE数据。

How can I return that information back? 如何退回该信息?
ie I want to be able to something to the effect of: 即我希望能够达到以下效果:

var result = MyClass.GetMyData("aaa",1);
var color = result.NAV_PROP.Color;

If I understand correctly this doesn't work because I am closing the context in the GetMyData method. 如果我正确理解,那将不起作用,因为我正在关闭GetMyData方法中的上下文。

如果您具有导航属性,只需包括它们:

return context.MY_TABLE.Include(x=>x.MY_CHILD_TABLEProperty).Where(x => x.MY_CODE == Code && x.MY_VERSION == version).FirstOrDefault();

There are two ways to do that, once you have lazyloading enabled (which is the default setting on EF). 启用延迟加载(这是EF的默认设置)后,有两种方法可以执行此操作。

1) Use the extension "Include" 1)使用扩展名“包含”

context.Table.Include(t => t.RelatedTable).Where(x => ..Condition..).FirstOrDefault();

If your relationship is configured to be a "Required" foreign key relationship, EF will understand you're doing a "Inner Join" 如果您的关系被配置为“必需”外键关系,EF将理解您正在执行“内部联接”

If your relationship is configured to be a "Nullable" (not required), EF will understand you're doing a "Left Join". 如果您的关系被配置为“可为空”(不是必需的),EF将理解您正在执行“左连接”。

2) Select the related data using a .Select before the data is enumerated. 2)在列举数据之前,使用.Select选择相关数据。

context.Table.Where(x = ..Conditions..).Select(s => 
     new { 
          RelatedTableColumn = s.RelatedTable.Column 
          ...
     }).FirstOrDefault();

On this case EF will understand you're doing a "Inner Join" like using "Include", but, it will only return your "Selected" columns, which results in better performance for bigger queries. 在这种情况下,EF会理解您正在执行“内部联接”,就像使用“包含”一样,但是,它只会返回“选定”列,这对于较大的查询会带来更好的性能。

Edit 1 编辑1

Ps*: If you can't access ".Include" extension, just add: ps *:如果您无法访问“ .include”扩展名,只需添加:

 using System.Data.Entity;

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

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