How to avoid loading a specific column in linq

Viewed 1335

In Linq-to-SQL, it's possible to get all data from an entity object via using the ToList method:

db.users.Tolist();

It is also possible to get multiple columns via the select method:

var users= db.users.Select(
                t => new
                {
                    t.c1,
                    t.c2,
                    t.c3,
                    .
                    .
                });

But I want to get all columns without one specific column like this:

db.users.exclude(t.c2).tolist();

Is there any way to solve this issue?

2 Answers

To Do dynamically crud operations , But [jqgrid] Doesn't Work With navigation Property And Lazy loading, I want to avoid loading navigation Property in backend Cod

Add db.Configuration.LazyLoadingEnabled = false; before your query.

db.Configuration.LazyLoadingEnabled = false;
db.users.Tolist();

If there are collections you do want to load you would have to use Include

db.Configuration.LazyLoadingEnabled = false;
db.users.Incude(x => x.Roles).Tolist();

OR

If you are returning with json.net, which is the standard included library, add JsonIgnore to the properties you do not want to serialize to the client. Example:

public class User {
  [JsonIgnore]
  public ICollection UsersRoles {get;set;}
}

Why are you trying to walk backwards?

Just select the columns you want and don't select the one you don't want

instead of selecting them all and excluding the one you don't want like you are doing here :

var users= db.users.Select(
                t => new
                {
                    t.c1,
                    t.c2,
                    t.c3,
                    .
                    .
                    .

                });

do this instead:

var users= from u in db.users

        select u.c1, u.c3, etc... ;  //Dont select what you don't want

Or this one would be ok too :

var users = from u in db.users

                select new 
                {
                    c1 = u.c1, 
                    c3 = u.c3
                }.ToList();
Related