简体   繁体   中英

How to use the where clause in entity framework?

I'm trying to query my EF Code First database so it will return all bookings that where made by the currently logged in user. I'm not quite getting the syntax correct somewhere, and I'm hoping someone can point me in the correct direction.

The two different ways I've tried to achieve this:

List<Booking> bookings = new List<Booking>();
string userid = User.Identity.GetUserId();
foreach(var b in db.Bookings.Where(b => b.Customer.Id == userid))
{
    bookings.Add(b);
}
string userid = User.Identity.GetUserId();
var bookings = db.Bookings.Include(b => b.Customer).Include(b => b.Invoice).Include(b => b.Payment).Include(b => b.Vehicle).Where(b => b.Customer.Id == userid);
return View(bookings.ToList());

None of these ways have returned any of the bookings in the database, so I'm sure my logic is wrong here somewhere. Any help would be appreciated.

In your first query, you forgot to include Customer navigation property, so the customer always fails and no bookings will return.

Although in your 2nd query, you have included customer, invoice and etc! In that case, only returns customers if they have a booking which their booking got an invoice, payment and etc.

This query should work with you:

string userid = User.Identity.GetUserId();
var bookings = db.Bookings
                 .Include(b => b.Customer)
                 .Where(b => b.Customer.Id == userid)
                 .ToList();

return View(bookings);

It seems you are using EF with EagerMode enabled, so you need to Include customer or any related fields in your where criteria.

My off-topic recommendation:

Please don't return entities that fetched directly from ORM. First, convert them into a DTO (with AutoMapper or any other object mappers) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM