tags:

views:

40

answers:

2

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?

+2  A: 
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.

Stephan
oh wow. i usually write in vb.net, had no idea you can do multiline inline functions in c#.
Shawn Simon
As Tomas noted this probably won't translate to SQL but in that case you could always just pull back the entities in their table forms, and then do this in the translation to the entity.
Stephan
+2  A: 

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...

Tomas Petricek