14

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?

VansFannel
  • 43,504
  • 101
  • 342
  • 588
  • 1
    possible duplicate of [LINQ to SQL - How to select specific columns and return strongly typed list](http://stackoverflow.com/questions/1094931/linq-to-sql-how-to-select-specific-columns-and-return-strongly-typed-list) – Iłya Bursov Oct 19 '13 at 06:30
  • 1
    By the way, IMHO this is bad design. You should never exposed your entities to your UI, Web Service, etc. You should have a DTO (Data Transfer Object) which basically is a POCO with only those fields that you want to expose. – Pepito Fernandez May 23 '14 at 13:51

4 Answers4

11

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.

2

another way like this,

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

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... ;
Jason Enochs
  • 1,380
  • 1
  • 12
  • 19
  • 1
    This syntax gives me a compile-time error "`;` expected". Did you mean to use the `new { u.UserId, u.Whatever, ... }` syntax for anonymous types? – Dai Dec 22 '14 at 19:43
  • 2
    No, you simply forgot the semicolon at the end or made a typo. Of course you don't type the "etc." shown in my example. after the last column listed, leave off the comma and terminate it with a semicolon... select u.UserId, u.AnotherColumn, u.LastColumn; – Jason Enochs Dec 23 '14 at 21:14
  • 2
    The way you typed it is rejected by the compiler. [Here](http://stackoverflow.com/a/6772286/75500) is how to select multiple columns. I'm updating that in your answer. – Shimmy Weitzhandler Apr 17 '15 at 00:17
0

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.

Brent Lamborn
  • 1,352
  • 3
  • 17
  • 37