Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I need to change this piece of code to entity framework

C#
string getQuerystring = queueListBox.Text.Substring(0, 4).Replace(" ", string.Empty);
queryString = "Select * from reservation where Id= '" + getQuerystring + "'";

query = new SqlCommand(queryString, connection);


What I have tried:

try to change this to entity framework
Posted
Updated 13-Apr-16 13:39pm

1 solution

This is a very basic operation in EF. I highly suggest you pick up a book on EF and work through it.

We can't tell you exactly what the code is going to be because we know NOTHING about your EF database setup, like your DbContext name. We don't know what you called your reservation table name, what the Id field is, ... nothing.

But, there's a couple of different ways of doing this:
var result = myDbContext.Reservations.SingleOrDefault(r => r.Id == queryId);

or
var result = myDbContext.Reservations.Where(r => r.Id == queryId).SingleOrDefault();

or
var result = from r in myDbContext.Reservations
             where r.Id == queryId
             select r;
 
Share this answer
 
v2
Comments
Matt T Heffron 13-Apr-16 19:53pm    
For consistency between the two ways, the SingleOrDefault probably should be Where.
SingleOrDefault will return either the only matching object, or null if zero or more than one matches.
Dave Kreskowiak 13-Apr-16 22:00pm    
Crap. I feel like crap. Probably why I missed that. I was paying too much attention to how crappy I feel.

Fixed.
Matt T Heffron 14-Apr-16 12:53pm    
They're still not quite equivalent.
The first two will set result to a single Reservation instance or null.
The third will set result to an IQueryable<Reservation>, possibly empty.
Dave Kreskowiak 14-Apr-16 13:57pm    
Yeah, I'm not going to worry about it. It's up to him to figure out how to map his business rules to an appropriate method.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900