开发者

LINQ - How can I give a child object in a select statement a reference to its parent?

I'm trying to do something like this:

        List<FundEntity> entities = this.tFunds
            .Select(f => new FundEntity() {
               ID = f.fundID,
               Name = f.name,
               CapitalCalls = f.tCapitalCalls
                    .Select(cc => new CapitalCall() {
                        ID =  cc.capitalCallID,
                        Description = cc.description,
                        FundEntity = // Should be the newly created Fund Entity object开发者_运维技巧
                    }).ToList()                   
            }).ToList();

I would like the each Capitalcall object to have a reference back to its FundEntity. Is this possible without creating a loop and setting each one manually?


List<FundEntity> entities = this.tFunds
        .Select(f => 
        {
           var parent = new FundEntity() {
               ID = f.fundID,
               Name = f.name,
               };
           parent.CapitalCalls = f.tCapitalCalls
                    .Select(cc => new CapitalCall() {
                    ID =  cc.capitalCallID,
                    Description = cc.description,
                    FundEntity =parent // Should be the newly created Fund Entity object
                });
            return parent;
        }.ToList()                   
        ).ToList();

That should give you the reference.


Is this LINQ in memory or LINQ to Entities/SQL?

  • In the first case, you can just create the entity and then set its CapitalCalls property imperatively (as in the example from Stephan)

  • In the second case, I'm afraid there is no way to do this in the LINQ query (because you cannot reference to the object that you're creating while it is being created, but you cannot use multiple statements, because the translator doesn't support that). However you could easily modify your database or Entity model to contain the reference you need...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜