Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework selection query

I am making a simple application for insert, update, delete, select data with Entity Framework
I already made insertion, deletion and select all data.

Now I want to select with where condition with filter of two fields
For ex : I have table with

userid
username
password
email

Now need selection like where email = "" and password = ""

I know how to write query in SQL but having not clues with entity framework.
Also need to store this result in datatable and looping solution both for learning purpose.
This can help many beginners

like image 780
Mer Hardik Avatar asked Sep 10 '13 11:09

Mer Hardik


2 Answers

Using Linq To Entities with lambda expression:

var result = dBContext.Account.Where(a=> a.email == "" && a.password =="").ToList();

Using Linq To Entities the less fancy way:

var result = (from a in dBContext.Account
              where a.email == "" && a.password ==""
              select a).ToList();

Lambda expressions are used most of the time. Some people find lambda's less readable. I think it's more a personal taste that depends from your background.

EDIT:

dbContext should be replaced by the name you gave your dbContext/Entities when setting up your Entitiy framework EDMX or Code First Classes.

Account should be replaced by the name of your table/Entity

To loop and edit the results you can do:

foreach(var account in results)
{
   //do something with the properties
   account.email = "[email protected]"
}

//store the changes again in the db
dbContext.SaveChanges();
like image 66
Beejee Avatar answered Sep 27 '22 17:09

Beejee


Use linq ex:

List<User> result = dbContext.Users.Where(o=> o.email == "" && o.password=="").ToList();

foreach(User u in result)
{
// do stuff
}

User u = new User();
u.Email = "[email protected]";

dbContext.Users.Add(u);
dbContext.Save(); //I think its Save()..
like image 20
jrb Avatar answered Sep 27 '22 17:09

jrb