Display result of linq query randomly in listview in Asp.net C# - asp.net

var getquest = (from q in dc.Exam_Questions
where q.ExamNumber == int.Parse(Examnumber)
select new
{
QuestionTitle = q.QuestionTitle,
correctanswers = q.correctanswers,
ID = q.ID,
});
ListView1.DataSource = getquest;
ListView1.DataBind();
How to display result of linq query randomly in listview in Asp.net C#?

You can create a random data by adding a guid property to your query. After that you order the result by this new property.
var getquest = (from q in dc.Exam_Questions
where q.ExamNumber == int.Parse(Examnumber)
select new
{
RandomId = Guid.NewGuid(),
QuestionTitle = q.QuestionTitle,
correctanswers = q.correctanswers,
ID = q.ID,
});
ListView1.DataSource = getquest.OrderBy(p => p.RandomId).ToList();
ListView1.DataBind();

Related

How to pass parameters to Oracle DbContext FromSql in Net Core

var list = db.SomeModels.FromSql("select id from table1 where rownum < :r",10).ToList();
gives me
System.ArgumentException: 'Invalid parameter binding Parameter name: r'
What am I missing. Can't find any docs on that
The following should work:
var row = new OracleParameter("r", OracleDbType.Int32);
row.Value = 10;
var list = db.SomeModels
.FromSql("select id from table1 where rownum < :r", new object[] { row })
.ToList();
To add multiple parameters, add more OracleParameter objects to the object array:
var row = new OracleParameter("r", OracleDbType.Int32);
row.Value = 10;
var nameParameter = new OracleParameter("name", OracleDbType.Varchar2);
nameParameter.Value = "John";
var list = db.SomeModels
.FromSql("select id from table1 where rownum < :r and firstname = :name", new object[] { row, nameParameter })
.ToList();
Unfortunately, like yourself I haven't found any proper documentation for it. I will edit the answer when I do.
The following code will also work (tested with Oracle.ManagedDataAccess.Core v2.19.31 and Microsoft.EntityFrameworkCore v2.2.6):
var list = db.SomeModels
.FromSql("select id from table1 where rownum < {0}", 10)
.ToList()

is there a way to get rid of DTO

I am using Entity Framework. I have the following query in which I get data using two tables Application and Employee connected by a foreign key EmployeeID in Application Table. The tables have 1-1 relationship .
Is there a way to simplify the following code and get rid of the DTO Employee1
which is the same as auto generated Employee class
public List<Employee1> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = (from a in context.Applications
join e in context.Employees on a.EmployeeID equals e.EmployeeID
where
(
a.ApplicationID == ApplicationID
)
select new Employee1
{
EmployeeID = e.EmployeeID,
SecondEmail = e.SecondEmail,
EmailID = e.EmailID,
Title = e.Title,
Name = e.Name,
Rank = e.Rank,
POBox = e.POBox,
Phone = e.Phone,
JoinDate = e.JoinDate,
Status = e.Status,
DepartmentID = e.DepartmentID.Value,
NameString = e.NameString,
Department = e.Department,
ParentDept = e.ParentDept,
DepartmentAr = e.DepartmentAr,
NameAr = e.NameAr,
NameStringAr = e.NameStringAr,
TitleAr = e.TitleAr
}).ToList();
return data;
}
If you need to return list of Employees, just select e which refers to Employee and don't use Employee1 as a DTO.
public List<Employee> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = (from a in context.Applications
join e in context.Employees on a.EmployeeID equals e.EmployeeID
where
(
a.ApplicationID == ApplicationID
)
select e).ToList();
return data;
}
Another way is this, which I would prefer because of readability:
public List<Employee> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = context.Applications.Where(p=>p.ApplicationID == ApplicationID).Select(p=>p.Employee).ToList();
return data;
}

Disable or checked previously selected items of checkboxlist?

i want to disable or checkd previously selected items. the selected item were saved in database as userid_checkbox iteams.i need to get selected items by a user. if user id is 10 and selected item is 2 then it will save in database 10_2. so i need to split it to get the second item number and use loop to disable the selected items. i have written as below
int user_id = Convert.ToInt16(Session["user_id"]);
ward w = new ward();
using (DataClassesDataContext db = new DataClassesDataContext())
{
List<string> bednum = (from j in db.wards where w.user_id == user_id select j.wbedno).ToList();
foreach (var bed in bednum)
{
string vals = bed.Split('_')[1];
cbList = (CheckBoxList)pnlControls.FindControl(vals);
// cbList.Items.Add(new ListItem(vals));
var query = from listItem in cbList.Items.Cast<ListItem>()
// join item in bednum on
where listItem.Value == bed
select listItem;
// var query = from l in cbList.Items
foreach (ListItem listItem in query)
listItem.Selected = true;
}
}
Change your code to this:
int user_id = Convert.ToInt16(Session["user_id"]);
CheckBoxList cbList = (CheckBoxList)pnlControls.FindControl("MyCheckBoxListID");
ward w = new ward();//Guessing ward is a class?
using (DataClassesDataContext db = new DataClassesDataContext())
{
List<string> bednum = (from j in db.wards where w.user_id == user_id select j.wbedno).ToList();
foreach (var bed in bednum)
{
string vals = bed.Split('_')[1];
ListItem listItem = cbList.Items.FindByValue(vals);
if (listItem != null) listItem.Selected = true;
}
}

Add parent row and add child for that new parent row

i am creating new record in 'Timecard' table and at the same time i want to create one record in 'TimecardStatusTrack' table using entity framework. i am able to create parent record but while adding child record i am getting exception. the code i have written is like
var fEmpManager = DependencyContainer.GetInstance<IBusinessService<FacilityEmployee>>();
int timecardStatusDidNotWork =
Convert.ToInt32(GeneralCodeId.TimeCardStatusDidNotWork, CultureInfo.InvariantCulture);
Timecard timecard = new Timecard();
TimecardStatusTrack timecardStatus = new TimecardStatusTrack();
try
{
var fEmp = fEmpManager.Where(w => w.JobId == jobId && w.AgencyBiddingProfile.AgencyCandidateId == agencyCandidateId).FirstOrDefault();
timecard.JobId = jobId;
timecard.AgencyCandidateId = agencyCandidateId;
timecard.WeekStartDate = Convert.ToDateTime(weekStartDate, CultureInfo.InvariantCulture);
timecard.WeekEndDate = Convert.ToDateTime(weekEndDate, CultureInfo.InvariantCulture);
timecard.FacilityEmployeeId = fEmp.Id;
timecard.FacilityId = fEmp.FacilityId;
timecard.TimecardStatusGCId = timecardStatusDidNotWork;
timecard.AddUser = SessionManager.AuthorizedInfo.UserId;
timecard.AddDate = DateTime.Now;
timecardStatus.TimecardStatusGCId = timecardStatusDidNotWork;
timecardStatus.AddUser = SessionManager.AuthorizedInfo.UserId;
timecardStatus.AddDate = DateTime.Now;
timecardStatus.UpdatedBy = SessionManager.AuthorizedInfo.UserId;
timecardStatus.Comments = string.Empty;
_ViewTimeCardBusibessService.Create(timecard);
timecard.TimecardStatusTracks.Add(timecardStatus);
_ViewTimeCardBusibessService.Update(timecard);
}
catch (Exception ex)
{
HandleValidationErrors(ex);
}
finally
{
DependencyContainer.ReleaseInstance(fEmpManager);
}

How to calculate count on of table column using group by clause in linq

I'm new to linq.
In c# I'm doing as follows to get the count of one column.
SELECT DispatcherName,
ActivityType,
CONVERT(BIGINT,COUNT(ActivityType)) AS Total
FROM ACTIVITYLOG
GROUP BY DispatcherName,
ActivityType
ORDER BY Total DESC
Can any one tell m,how I can achieve the same thing using LINQ.
Update:
HI I did as follows and got the reslut.
But I'm not able to convert result to datatable.
this is how I did.
here dt is datatabe with two columns Dispatchername and ActivityType.
var query1 = from p in dt.AsEnumerable()
group p by new
{
DispatcherName = p.Field<string>("Dispatchername"),
Activity = p.Field<string>("ActivityType"),
}
into pgroup
let count = pgroup.Count()
orderby count
select new
{
Count = count,
DispatcherName = pgroup.Key.DispatcherName,
Activity = pgroup.Key.Activity
};
pls help me out asap.
from c in ACTIVITYLOG
group c by new {c.DispatcherName, c.ActivityType} into g
orderby g.Count() descending
select new { g.Key.DispatcherName, g.Key.ActivityType, Total = g.Count() }
If you want your results returned back to a DataTable, one option is to use the CopyToDataTable method.
Here's a live example: http://rextester.com/XHX48973
This method basically requires you to create a dummy table in order to use its NewRow method - the only way to create a DataRow, which is required by CopyToDataTable.
var result = dt.AsEnumerable()
.GroupBy(p => new {
DispatcherName = p.Field<string>("DispatcherName"),
Activity = p.Field<string>("ActivityType")})
.Select(p => {
var row = dummy.NewRow();
row["Activity"] = p.Key.Activity;
row["DispatcherName"] = p.Key.DispatcherName;
row["Count"] = p.Count();
return row;
})
.CopyToDataTable();
Perhaps a better way might be just fill in the rows directly, by converting to a List<T> and then using ForEach.
DataTable dummy = new DataTable();
dummy.Columns.Add("DispatcherName",typeof(string));
dummy.Columns.Add("Activity",typeof(string));
dummy.Columns.Add("Count",typeof(int));
dt.AsEnumerable()
.GroupBy(p => new { DispatcherName = p.Field<string>("DispatcherName"),
Activity = p.Field<string>("ActivityType")})
.ToList()
.ForEach(p => {
var row = dummy.NewRow();
row["Activity"] = p.Key.Activity;
row["DispatcherName"] = p.Key.DispatcherName;
row["Count"] = p.Count();
dummy.Rows.Add(row);
});
Live example: http://rextester.com/TFZNEO48009
This should do the trick:
IList<ACTIVITYLOG> allActivityLogs;
var result = (from c in allActivityLogs
select new
{
DispatcherName = c.DispatcherName,
ActivityType = c.ActivityType,
Total = c.ActivityType.Count
}).OrderByDescending(x => x.Total)
.GroupBy(x => new { x.DispatcherName, x.ActivityType });
You only need to substitute the allActivityLogs collection with the actual collection of your entities.

Resources