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;
}
}
Related
In my application from the view someone pressed the Approve button, controller will collect the Main Id of the request. Here I want to update 3rd table Approval_Status column to true. I passed the main Id and got the 3rd table Id which I want to update record to the variable.
int PartyId = db.ApprovalProcess.Where(x => x.Req_Id == id).ToList().First().Id;
and then I wrote this code to pass the value. But it wont work. Can I get a help for this (question will seems like easy to you, but i want to tell you that I'm self learning ASP.NET MVC these days. So some stuff still I couldn't get)
Here is my database structure. Main table name is AppRequest, 2nd table is ApprovalProcess and the 3rd one is Approval_Parties.
This is my current code:
public ActionResult ApproveRequest(int? id)
{
int PartyId = db.ApprovalProcess.Where(x => x.Req_Id == id).ToList().First().Id;
if (ModelState.IsValid)
{
// model.Approved_Date = DateTime.Now;
ApprovalParty approvalParty = new ApprovalParty();
approvalParty.Approve_Status = true;
db.SaveChanges();
return RedirectToAction("Index");
}
}
I think I'm missing the code that which record should update in the table that already assigned that Id to the PartyId.
Something like this would work:
public ActionResult ApproveRequest(int? id)
{
ApprovalProcess approvalProcess = db.ApprovalProcess.FirsOrDefault(x => x.Req_Id == id);
if (approvalProcess != null)
{
ApprovalParty approvalParty = db.Approval_Parties.FirsOrDefault(x => x.ApprovalProcess_Id == approvalProcess.Id);
if (approvalParty != null)
{
approvalParty.Approve_Status = true;
approvalParty.Approved_Date = DateTime.Now;
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
I'm trying to access the list of attachments sent by the user to the skype bot that I'm developing.
Here is how I access the attachment details ,
public async Task<HttpResponseMessage> Post([FromBody]Activity message)
{
if (message.Attachments != null)
{
if (message.Attachments.Count > 0)
{
List<Attachment> attachmentList = message.Attachments.ToList();
foreach (var item in attachmentList)
{
var name = item.Name;
var content = item.Content;
}
}
}
}
But I get null for the following even though the attachment count is greater than zero,
var name = item.Name;
var content = item.Content;
Am I doing this right?
Maybe do something like this...
List<Attachment> attachmentList = message?.Attachments?.Where(x => x != null)?.ToList() ?? new List<Attachment>();
This would hopefully always set attachmentList to an empty list or a list containing non null items?
I am passing a query result from the controller to a view through a Viewbag but when looping through the Viewbag result I get the error 'object' does not contain a definition for 'Ratings' even though it does show up when debugging. I am not using a model for the query so I cannot cast the list.
How do I send through the list from the query or the query results itself to the view to so I loop through and extract the data?
Controller
var AppQuery = (from ans in db.Answers
join ques in db.Questions on ans.QuestionID equals ques.QuestionID
join resp in db.Responses on ans.ResponseID equals resp.ResponseID
join sec in db.Sections on ques.SectionID equals sec.SectionID
where resp.ResponseID == ID && ques.SubSectionName != null
select new { SectionName = sec.SectionName, RatingAnswer = ans.RatingAnswer })
.GroupBy(a => a.SectionName)
.Select(a => new { SectionName = a.Key, Ratings = a.Sum(s => s.RatingAnswer) });
ViewBag.Results = AppQuery.ToList();
View
#{var Results = ViewBag.Results;}
#foreach (var item in Results)
{
var style = "active";
var condition = "";
if (item.Ratings >= 90)
{
style = "success";
condition = "Excellent";
}
else if (item.Ratings < 50)
{
style = "danger";
condition = "Critical";
}
else
{
style = "active";
condition = "Stable";
}
<tr class="#style">
<td>#item.SectionName</td>
<td>#item.Ratings</td>
<td>#condition</td>
</tr>
}
Thanks for the help!
This is the expected behaviour!. Because you set a collection of anonymous objects to your ViewBag.
You should be using a strongly typed view model.
public class RatingVm
{
public string SectionName { set;get;}
public int Ratings { set;get;}
}
and in your action method,
public ActionResult Create()
{
var results= (from ans in db.Answers
join ques in db.Questions on ans.QuestionID equals ques.QuestionID
join resp in db.Responses on ans.ResponseID equals resp.ResponseID
join sec in db.Sections on ques.SectionID equals sec.SectionID
where resp.ResponseID == ID && ques.SubSectionName != null
select new { SectionName = sec.SectionName,
RatingAnswer = ans.RatingAnswer })
.GroupBy(a => a.SectionName)
.Select(a => new RatingVm { SectionName = a.Key,
Ratings = a.Sum(s => s.RatingAnswer) }).ToList();
return View(results);
}
Now your view should be strongly typed to the type of data we are passing from our action method, which is a collection of RatingVm
#model List<RatingVm>
<h1>Ratings</h1>
#foreach(var item in Model)
{
<p>#item.SectionName</p>
<p>#item.Ratings</p>
}
I am trying to Get some data from Database and Bind them in Drop-Down list.. But getting following error : -
public virtual List<HRM_PersonalInformations>GetAssignePerson(String OCODE, int dptID){
var query = (context.HRM_PersonalInformations.Where
(c => c.OCODE == OCODE && c.DepartmentId == dptID)
.Select(c => new {FullName = (c.FirstName + ' ' + c.LastName), c.EID})).ToList();
return query; // It indicate error line
}
After that I am trying to Bind data in dropdown list and my code is following : -
private void FillAssignPerson()
{
try
{
string OCODE = ((SessionUser)Session["SessionUser"]).OCode;
int dptId = Convert.ToInt32(ddlAssignPerDept.SelectedValue);
var row = enquiryBll.GetAssignePerson(OCODE, dptId).ToList();
//const string list = "SELECT FirstName + ' ' + LastName AS FullName, EID, FirstName, LastName " +
// "FROM HRM_PersonalInformations " +
// "ORDER BY EID ASC"
if (row.Count > 0)
{
ddlAssignPerson.Items.Clear();
ddlAssignPerson.DataSource = row;
ddlAssignPerson.DataTextField = "FullName";
ddlAssignPerson.DataValueField = "EID";
ddlAssignPerson.DataBind();
ddlAssignPerson.Items.Insert(0, new ListItem("----- Select One -----", "0"));
ddlAssignPerson.AppendDataBoundItems = false;
}
}
Is it right way ?? Can anyone help me ? Thanks for Advance ..
Well, in your projection you have:
c => new {FullName = (c.FirstName + ' ' + c.LastName), c.EID}
That's creating an instance of an anonymous typoe - not an instance of HRM_PersonalInformations. If those are the only two properties you need in HRM_PersonalInformations, you could just change it to:
c => new HRM_PersonalInformations {
FullName = (c.FirstName + ' ' + c.LastName),
EID = c.EID
}
Or judging by your query, you may not need a projection at all. You may be fine with:
return context.HRM_PersonalInformations
.Where(c => c.OCODE == OCODE && c.DepartmentId == dptID)
.ToList();
Alternatively, if you only need those properties and don't really need the items of your list to be instances of HRM_PersonalInformations, you could just change the method's signature to be:
public virtual IList GetAssignePerson(...)
and keep the body as it is. You can't explicitly write a method declaration which specifies the anonymous type, because it doesn't have a name - but List<T> implements IList, so the above will certainly compile... it will fail if you later try to cast an element in it to HRM_PersonalInformations though.
EDIT: If the string concatenation is a problem, you might need to do that client-side. For example:
public IList GetAssignePerson(String OCODE, int dptID) {
return context.HRM_PersonalInformations
.Where(c => c.OCODE == OCODE && c.DepartmentId == dptID)
.Select(c => new { c.FirstName, c.LastName, c.EID })
.AsEnumerable() // Do the rest client-side
.Select(c => new {
FullName = c.FirstName + " " + c.LastName,
c.EID
})
.ToList();
}
This methods awaits you HRM_PersonalInformations , why are you return anonymous type ?
It is useful to go back to the expected type
Try this code
.Select(c => new HRM_PersonalInformations()
{
FullName = c.FirstName
// set other prop
});
this is a simple sample,
If you want to customize data business process or UI process you need a new model for example You want to display full name in Dropdown so ,
Add new folder MyCustomizeModels
Add new class DropdownLookUpDecimal in MyCustomizeModels
this DropdownLookUpDecimal class.
public class DropdownLookUpDecimal
{
public decimal Value { get; set; }
public string Text { get; set; }
}
You can use this class all Dropdown in the project.
public List<DropdownLookUpDecimal>GetAssignePerson(string oCode, int dptID)
{
var query = context.HRM_PersonalInformations.Where
(c => c.OCODE == oCode&& c.DepartmentId == dptID)
.Select(c => new DropdownLookUpDecimal
{
Text = c.FirstName + ' ' + c.LastName,
Value = c.EID
});
return query.ToList();
}
Just create new .cs and fill the list with the class and return List.
I hope it helped
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();