简体   繁体   English

实体框架-仅加载导航属性中的某些行

[英]Entity Framework - Loading only certain rows in navigational property

I have the classes 我有课

Address
PeopleAddress    //join table with a column called current
People           // my main table, with a IList<PeopleAddress>

modelBuilder.Entity<People>()
            .HasMany<PeopleAddress>(m => m.CurrentAddresses)
            .WithRequired()
            .HasForeignKey(m => m.PeopleId);

I (always) want to load only PeopleAddress's in people where PeopleAddress.Current == 1. rows with PeopleAddress.Current == 0 is not required for the application. 我(总是)只希望在PeopleAddress.Current == 1的人中加载PeopleAddress。应用程序不需要使用PeopleAddress.Current == 0的行。 How do I achieve this? 我该如何实现? Is this possible? 这可能吗? Thank you. 谢谢。

PS: I cant not use Include as the context is instantiated in a lot of places and I need to do it in OnModelCreating(DbModelBuilder modelBuilder) PS:我不能使用Include因为在很多地方实例化了上下文,我需要在OnModelCreating(DbModelBuilder modelBuilder)

For this to work lazy loading should be disabled giving you full control of which data is loaded. 为此,应禁用延迟加载,以完全控制要加载的数据。

Do the query on the PeopleAddress table and make sure the People data gets loaded as well via the navigational property in PeopleAddress. 在PeopleAddress表上进行查询,并确保通过PeopleAddress中的导航属性也加载了People数据。

public virtual People People { get; set; }

PeopleAddress.Include(pa => pa.People).Where(pa => pa.Current == 1)

Try it 试试吧

context.People.Include("PeopleAddress")
              .Select(t=> new { t,
                                PeopleAddress= t.PeopleAddress
                                                .Where(p=>p.Current==1)});

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

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