Bono
Bono

Reputation: 4869

Linq - Select record from database by id

I'm trying to get a record from the database with an id I specified. However I'm having difficulties creating the correct Linq query.
First off this is two of the things I've tried, but which don't seem to work.

var query_result = from d in db.Departments
                   where d.id == id
                   select d;

Here I try to select the department which follows my given id. However in my Department class the id attribute is private. Which I would like to keep that way, in compliance with normal OOP.

Before that I tried doing this:

var query_result = from d in db.Departments
                   where d.getId() == id
                   select d;

In this case I'm using the getter for the id, but that gives me the following error:

Method 'Int32 getId()' has no supported translation to SQL.

I've tried looking around but I can't seem to find a conclusive answer for something that should be, in my opinion, very simple. I do see a lot of examples access the class attributes directly, but that would mean making them public. Unless I'm missing something I wouldn't really want to go that way.

I'm not very experienced in Linq (or c# for that matter). Thanks in advance.

Upvotes: 1

Views: 8278

Answers (2)

krillgar
krillgar

Reputation: 12815

If you're using Entity Framework, then you can't declare either the get or set as private, or else Entity Framework won't be able to access it either.

This is what you're looking for to ensure that the outside code is unable to set the IDs:

public int Id { get; protected internal set; }

Upvotes: 2

Bill Sambrone
Bill Sambrone

Reputation: 4464

Your current query is returning a list. Sounds like you need a single record? For that, use this:

var recordDesired = db.Departments.FirstOrDefault(d => d.id == id);

Assuming 'id' is an int defined somewhere, and the 'id' property is also int. Are you using entity framework by any chance? If so, I believe the 'id' property needs to have both a public getter and a public setter. I hear you on not exposing the ID to your end client application. One option would involving using DTO's (data transfer objects) to translate all the goodness that the database spews out and wrapping it in a simple class that only exposes the properties your end application cares about.

Upvotes: 2

Related Questions