Showing linked table items in a controller/view - asp.net

I have a room class, which has 3 linked tables, Property, Sex (as in Male/Female), Stage.
I can get the Index controller to return the linked table items, by using Include:
var rooms = db.Rooms.Include(r => r.Property).Include(r => r.Sex).Include(r => r.Stage);
What I don't know is, how to you include these linked table items in the Details controller:
Room room = db.Rooms.Find(id);
The full controllers are listed below:
//
// GET: /Room/
public ActionResult Index()
{
var rooms = db.Rooms.Include(r => r.Property).Include(r => r.Sex).Include(r => r.Stage);
return View(rooms.ToList());
}
//
// GET: /Room/Details/5
public ActionResult Details(int id = 0)
{
Room room = db.Rooms.Find(id);
if (room == null)
{
return HttpNotFound();
}
return View(room);
}
Thanks for any help,
Mark

After Include statments you could use LINQ's SingleOrDefault method
Like this:
Room room = db.Rooms.Include(r => r.Property)
.Include(r => r.Sex)
.Include(r => r.Stage)
.SingleOrDefault(r => r.Id = id);

Related

Querying data from Table and passing to view

Need help with this coding.
Here I want to get request details from the main request table which is called "AppRequest". Here I have queried some requests and need to load the main details of the request from the AppRequest table. In the "ListRequesDropDown" is getting the main request ids from the AppRequest. So I want to pass that request-id data to the view. Currently "return View(db.AppRequest.ToList());" will shows the all the requests.
public class PendingRequestMController : Controller
{
private zSqlDb db = new zSqlDb();
// GET: PendingRequests to manager view
public ActionResult Index()
{
//Checking User ID
var UsrID = (User.Identity as ClaimsIdentity).Claims.Where(c => c.Type == "UserId").FirstOrDefault();
string UsrIDT = UsrID.Value;
// Checking is there any pending request to the above user ID
List <int> PendingRequestsforAprv = db.ApproveParties.ToList().Where(r => r.Approver_Id == int.Parse(UsrIDT ) && r.Approve_Status==false).ToList().
Select(x => x.ApprovalProcess_Id).ToList();
List<int> ReqTypeDropDown = db.ApprovalProcess.Where(r => PendingRequestsforAprv.Contains( r.Id )).Select(x => x.Req_Id).ToList();
return View(db.AppRequest.ToList());
}
}

How to order in ASP.NET MVC?

I have very complex code. I'm developing a web application for many restaurants where people can order online. I have two tables and models for Order, which contains information about User, and OrderDetails which has MenuItems. I created ShoppingCartController which has a ProcessOrder action
public ActionResult ProcessOrder(FormCollection frc)
{
List<Cart> lstCart = (List<Cart>)Session[strCart];
Order order = new Order()
{
Name = frc["Name"],
UserId = User.Identity.GetUserId(),
OrderTime = DateTimeOffset.UtcNow,
PaymentType = "Cash",
Status = "Processing"
};
db.Orders.Add(order);
db.SaveChanges();
foreach (Cart cart in lstCart)
{
OrderDetail orderDetail = new OrderDetail()
{
OrderId = order.Id,
MenuId = cart.Menu.Id,
Quantity = cart.Quantity,
Price = cart.Menu.Price,
RestaurantId = cart.Menu.RestaurantId
};
db.OrderDetails.Add(orderDetail);
db.SaveChanges();
}
Session.Remove(strCart);
return View("OrderSuccess");
}
Also I created an OrderController for displaying list of orders:
public ActionResult Index(int? restaurantId = null)
{
var orders = db.Orders.Include(o => o.User)
.Include(p => p.OrderDetails)
.OrderByDescending(x => x.Id);
return View(orders.ToList());
}
Here I just added restaurantId parameter.
And now I want to display orders by RestaurantId. I thought about taking RestaurantId from OrderDetails->Menu->RestaurantId, but I don't think that it works because OrderDetails of each order can have many RestaurantId.
Should I add RestaurantId column in Order table? Can you suggest an approach?
Order detail has both orderId and RestaurantId thats the table you need to query from!

Correctly implementing a search function

I have a search function that searches against a user table and a Vehicle Registration table. There is a one to many relationship between the tables.
The VehicleNumbis a collection of number where I've inserted '-' to make it more readable. Keep in mind that in my DB, the numbers do not have dashes.
So when I'm searching, I removed the '-' and replaced it with an empty string.
So for example, if I have 12345678 in my table, I would have placed a '-' like this 12-345678. So when I'm searching for 12-345678, I expect to get the
the user result.
The issue I'm encountering is that I can not get any result back. Where am I going wrong?
public IQueryable <MyModel> Method(string search)
{
var userResult = _context.User.Select(u => new MyModel()
{
UserName = u.UserName,
FullName = u.FullName,
Status = u.MStatus,
VehicleNumb = u.Vehicle
.Where(v => v.Registration.VehicleNumb.Any()
&& v.Registration.VehicleNumb != null)
.Select(x => v.Registration.VehicleNumb.Insert(2, "-"))
});
if(!string.IsNullOrEmpty(search.Replace("-", "")))
{
foreach(var item in userResult)
{
foreach(var item2 in item.VehicleNumb)
{
userResult = userResult
.Where(x => item2.Replace("-", "").Contains(search.Replace("-", "")));
}
}
return userResult;
}
}

Complex LINQ query - multiple table relationships

I have a books database, which has an ICollection of authors. I want to return the author object based on the AuthorId using LINQ.
Book db
int BookId
string Name { get; set; }
public ICollection<Author> Authors { get; set; }
Author db
int AuthorId
string Name
ICollection<Quote> Quotes { get; set; }
ICollection<Penname> Pennames { get; set; } - Edit: Added for clarity
I have tried:
var test = _context.Book.Include(x => x.Authors).Include("Authors.Quotes")
.Select(y => y.Authors)
Which gave me:
EntityQueryable<ICollection<Authors>>
[0] {HashSet<Author>} [0]{Author} [1]{Author} [3]{Author}
[1] {HashSet<Author>} [0]{Author} [1]{Author}
[2] {HashSet<Author>} [0]{Author} [1]{Author}
I just can't figure out how to iterate though the Authors in the Authors list. Something like the below:
var id = 2
var test = _context.Book.Include(x => x.Authors).Include("Authors.Quotes")
.Select(y => y.Authors.Select(x => x.Author).Where(x => x.AuthorId == id))
If I ever do a major update I might use elastic...
Update #Marko Papic:
Thanks. Weirdly if I use the below to get a list of books with authors, I get the quotes and pennames lists populated as I expect
var test = _context.Book.Include(x => x.Authors)
.ThenInclude(x => x.Quotes)
.Include(x => x.Authors)
.ThenInclude(x => x.Pennames)
However if I use SelectMany, then the quotes and pennames end up as null
var test = _context.Book.Include(x => x.Authors)
.ThenInclude(x => x.Quotes)
.Include(x => x.Authors)
.ThenInclude(x => x.Pennames)
.SelectMany(x => x.Authors).Where(x => x.AuthorId == id);
Author myauthor
int AuthorId = 2
string Name = "Bob"
ICollection<Quote> Quotes = null
ICollection<Penname> Pennames = null
You can use SelectMany:
var test = _context.Book.Include(x => x.Authors).ThenInclude(x => x.Quotes)
.SelectMany(x => x.Authors).Where(x => x.AuthorId == id);
I think the includes are ignored because the result type of the query is not the same of the type of your dbset with when you start, from the documentation:
If you change the query so that it no longer returns instances of the
entity type that the query began with, then the include operators are
ignored.
I assume the relationship between Books and Authors is many to many, if that is the case then this is how I would do your query:
var query=_context.Authors.Include(a=>a.Books)
.Include(a=>a.Quotes)
.Include(a=>a.Pennames)
.Where(a=> a.AuthorId == id);

get all the values in Sql table using foreach

I need to get all the Ids' from the table "StaffSectionInCharge", it has only two columns StaffId and SectionId, I have values of StaffId and StudentId.....the problem is I can't get the records directly to this table.....am using entity framework and the design of this table is
[EdmRelationshipNavigationPropertyAttribute("Model", "StaffSectionInCharge", "Section")]
public EntityCollection<Section> Sections
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Section>("Model.StaffSectionInCharge", "Section");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Section>("Model.StaffSectionInCharge", "Section", value);
}
}
}
I can access this table through staff table like
Staff staff = buDataEntities.Staffs.First(s => s.StaffId == StaffId);
Section section = buDataEntities.Sections.First(s => s.SectionId == SectionId);
staff.Sections.Add(section);
buDataEntities.savechanges();
like this I can add the records to this StaffSectionInCharge table....
here I want to get all the StaffIds for the corresponding SectionId
I tried getting like
DataAccess.Staff staffs = new DataAccess.Staff();
foreach (int staff in staffs.Sections.Select(s=>s.SectionId))
{
}
but its not working, can anyone help me here
var staffIds = buDataEntities.Staffs
.Where(st => st.Sections.Any(se => se.SectionId == SectionId))
.Select(st => st.StaffId)
.ToList();
or
var staffIds = buDataEntities.Sections
.Where(se => se.SectionId == SectionId)
.SelectMany(se => se.Staffs.Select(st => st.StaffId))
.Distinct()
.ToList();
Both options should work. If SectionId is the primary key of Section you can smplify the second code to:
var staffIds = buDataEntities.Sections
.Where(se => se.SectionId == SectionId)
.Select(se => se.Staffs.Select(st => st.StaffId))
.SingleOrDefault();

Resources