简体   繁体   中英

How to filter child tables with EF4?

I have these tables

CREATE TABLE parent
( 
     id               NUMBER(10, 0) NOT NULL, 
     name             VARCHAR2(100 CHAR) NOT NULL, 
     primary key (id), 
)

CREATE TABLE child
( 
     id               NUMBER(10, 0) NOT NULL, 
     name             VARCHAR2(100 CHAR) NOT NULL, 
     conclusion       DATE,
     parent_id        NUMBER(10, 0) NOT NULL,
)

ALTER TABLE child ADD constraint foreign key (parent_id) references parent; 

I want to get a List<Parent> where each Parent.Child has only elements where !CONCLUSION.HasValue()

var result = (from p in Parent
              select new Parent()
              {
                id = p.id,
                child = (from c in Child
                         where c.parent_id = p.id &&
                         !c.conclusion.HasValue()
                         select c).ToList() 
              }).ToList();

This is not tested but it should do the job

A second option is to

var parents = context.Parents.ToList();
foreach(var parent in parents)
{
    var invalidChildren = parent.CHILD
        .Where(child => child.CONCLUSION.HasValue())
        .ToArray();
    foreach(var invalid in invalidChildren)
    {
        parent.CHILD.Remove(invalid);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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