Expert wanna be
Expert wanna be

Reputation: 10624

C#, entity framework, linq how to exclude property

public class MyObj
{
    [Key]
    public int id {get; set;}
    public string test1 {get; set;}
    public string test2 {get; set;}
    public int test3 {get; set;}
    public int test4 {get; set;}
    public int test5 {get; set;}
    public int? test6 {get; set;}
    public DateTime? test7 {get; set;}
    public string test8 {get; set;}
    public string test9 {get; set;}
    public string test10 {get; set;}
    public string test11 {get; set;}
    public string test12 {get; set;}
    public DateTime? test13 {get; set;}
    public DateTime? test14 {get; set;}
    public DateTime? test15 {get; set;}
    public string test16 {get; set;}
    public string tes17 {get; set;}
    public int test18 {get; set;}
    public DateTime? test19 {get; set;}
    public bool test20 {get; set;}

    [ForeignKey("test3")]
    public virtual Child1 child1 { get; set; }
    [ForeignKey("test4")]
    public virtual Child2 child2 { get; set; }
    [ForeignKey("test5")]
    public virtual Child3 child3 { get; set; }
    [ForeignKey("test18")]
    public virtual Child4 child4 { get; set; }

    public virtual ICollection<Child1> child5 { get; set; }
}


var myobj = unitwork.myobjRepository.get();

I just want to pull id and test 1 to test20, without child1, child2, child3, child4 and child5.

For now, I do,

myobj.Select(x => new {
    id = x.id,
    test1 = x.test1
    ...
    ...
    test20 = x.test20
})); 

but I don't think this is right way.. Please advise me,

Upvotes: 0

Views: 2214

Answers (2)

100r
100r

Reputation: 1104

What is the reason you want to do this? If you are thinking in terms of not to overload sql server, you should check lazy loading. child1, child2, child3, child4, child5 won't be loaded untill you access those properties, and you'll have MyObj class (object) available. If you do it like you did, you endup with anonimous object. It might be ok in some scenarios but not in other. What also might be a solution is to create another class without unnecesery field and make select into instance of that new class.

myobj.Select(x => new NewClass() {
id = x.id,
test1 = x.test1
...
...
test20 = x.test20
})); 

Upvotes: 0

D Stanley
D Stanley

Reputation: 152501

If the property names are the same it could be slightly simpler:

myobj.Select(x => new {
    x.id,
    x.test1
    ...
    ...
    x.test20
})); 

If you are just projecting properties with no transformation the anonymous type will use the same property names.

If you're concerned about creating an anonymous type, then you could create a named type that has only the properties you need and project to that, but there's nothing wrong with using an anonymous type from what you've shown.

Upvotes: 2

Related Questions