2

I got the following LINQ Expression:

Context.TableOne.Select(
            one =>
            new
            {
                one.Column1,
                one.Column2,
                one.Column3,
                one.Column4,
                one.Column5,
                one.Column6,
                one.Column7,
                one.Column8,
                one.Column9,
                TwoCount = one.TableTwo.Count()
            });

When I select it as this:

Context.TableOne.Select(
            one =>
            new
            {
                One = one,
                TwoCount = one.TableTwo.Count()
            });

I would have gotten a nested property "One" containing all the fields of "one". This would require me (for example in a datagrid) to specify the FieldNames One.Column1 or One.Column2 instead of Column1 or Column2

Is it possible to include the TwoCount = one.TableTwo.Count()-Statement without needing to specify each and every column in this expression?

4

5 回答 5

1

You can select the whole entity instead:

Context.TableOne.Select(one => new {
    One = one,
    TwoCount = one.TableTwo.Count()
});
于 2012-11-27T14:07:18.907 回答
0

Yes, although I am confused as to why you think you need to select all of the columns in the first place.

于 2012-11-27T14:07:36.040 回答
0

Select the whole object, not each of its properties.

Context.TableOne.Select(
    one =>
        new
        {
            One = one,
            TwoCount = one.TableTwo.Count()
        });
于 2012-11-27T14:08:02.687 回答
0

When you use new {....} you are creating a new anonymous type. You are then setting the properties on that type with the object initializer syntax. It may be easier to understand if we break this down to what is actually happening.

First you are creating a new type Foo. Let's simplify this to 3 properties

public class Foo
{
    public object Column1 { get; set; }
    public object Column2 { get; set; }
    public int TwoCount { get; set; }
}

Now, let's just look at the lambda expression that is your select. We can extract this to a function like below.

public Foo CreateFoo(TableOne one)
{
    Foo foo = new Foo();
    foo.Column1 = one.Column1;
    foo.Column2 = one.Column2;
    foo.TwoCount = one.TableTwo.Count();

    return foo;
}

As you can see, we must set each property. We could encapsulate this logic in a constructor or somewhere else in class Foo because it is not an anonymous type. However, with an anonymous type, there isn't must you can do.

于 2012-11-27T14:37:51.377 回答
0

For everyone using EntityFramework, I've got the following solution for you:

Create a partial class in your TableOne Namespace and add a new property there:

public partial class TableOne
{
    public int TwoCount { get { return Two.Count; } }
}

This way you can just select the whole entity: var result = Context.TableOne;

于 2012-11-27T14:56:26.340 回答