VansFannel
VansFannel

Reputation: 45921

Exclude a column from a select using LINQ

I'm developing a WCF RESTful web service with Entity Framework Code First.

I have a table Users with a lot of columns. I do this to get an specific user:

context.Configuration.ProxyCreationEnabled = false;
var users = from u in context.Users
            where u.UserId == userId
            select u;

On this table, there is a password column, and I don't want return this column.

How can I exclude password column from that select?

Upvotes: 16

Views: 34774

Answers (5)

bobt
bobt

Reputation: 585

Yes, you can run LINQ with certain columns excluded:

  1. Store list of all columns in an array of string. E.g.

    var arrayOfColNames = dbContext.Model.FindEntityType(typeof(TableName)) .GetProperties().Select(x => x.Relational().ColumnName).ToArray() )

  2. Remove the unwanted columns from the above array of string. E.g.

    arrayOfColNames = arrayOfColNames .Where(w => !w.Equals("password")).ToArray();

  3. Run your LINQ select using the above filtered array of strings : https://stackoverflow.com/a/45205267/19386398

Upvotes: 0

Brent Lamborn
Brent Lamborn

Reputation: 1390

You can create more than one LINQ object per table. I'd create one with the field you need and one without. It makes CRUD operations more difficult though.

Upvotes: 0

Jason Enochs
Jason Enochs

Reputation: 1506

Specify each column that you do want in your select statement:

var users = from u in context.Users

        where u.UserId == userId

        select u.UserId, u.Watever, etc... ;

Upvotes: 2

user2815037
user2815037

Reputation:

another way like this,

   var users = from u in context.Users
                where u.UserId == userId
                select new 
                {
                    col1 = u.UserId, 
                    col2 = u.Watever
                }.ToList();

Upvotes: 2

Digvijay Verma
Digvijay Verma

Reputation: 326

Its sad to say but NO

You do not have option to directly exclude any particular column. You may go with lazy loading of columns.

The easiest and non-liking method would be to include columns which you want.

Upvotes: 14

Related Questions