linq to entity does not recognize the method - asp.net-mvc

I need to call a method FormatCourseTitle() from linq query but receive error message "Linq to Entity does not recognize the method FormatCourseTitle..." How to solve this problem?
public ActionResult Index()
{
var searchResults = (from a in db.Courses
join b in db.Summary on
new { subject = a.subject, catalog = a.catalog, coursetitle = FormatCourseTitle(a.coursetitle) } equals
new { subject = b.Subject, catalog = b.Catalogno, coursetitle = b.CourseTitle } into ab
from b in ab.DefaultIfEmpty()
where a.Active == true
select new JoinModel
{
Courses = a,
Summary2020 = b
} ).ToList();
return View(searResults);
}
public class JoinModel
{
[Key]
public int Id { get; set; }
public Courselist Courses { get; set; }
public Contentsummary Summary { get; set; }
}
public string FormatCourseTitle(string courseTitle)
{
//find if last three characters are " or"
string[] words = courseTitle.Trim().ToLower().Split(' ');
int j = words.Count();
string tempStr = string.Empty;
if (words[j] == "or")
{
tempStr = courseTitle.Substring(0, courseTitle.Length - 3);
}
else
{
tempStr = courseTitle;
}
return tempStr;
}

You should use extension method as
public static class StringHelper
{
public static string FormatCourseTitle(this string courseTitle)
{
//find if last three characters are " or"
string[] words = courseTitle.Trim().ToLower().Split(' ');
int j = words.Count();
string tempStr = string.Empty;
if (words[j] == "or")
{
tempStr = courseTitle.Substring(0, courseTitle.Length - 3);
}
else
{
tempStr = courseTitle;
}
return tempStr;
}
}
Change query to
var searchResults = (from a in db.Courses
join b in db.Summary on
new { subject = a.subject, catalog = a.catalog, coursetitle = a.coursetitle.FormatCourseTitle() } equals
new { subject = b.Subject, catalog = b.Catalogno, coursetitle = b.CourseTitle } into ab
from b in ab.DefaultIfEmpty()
where a.Active == true
select new JoinModel
{
Courses = a,
Summary2020 = b
} ).ToList();

I find a way to add condition in linq query to solve this problem.
var searchResults = (from a in db.Courses
join b in db.Summary on
new { subject = a.subject, catalog = a.catalog, coursetitle = a.coursetitle.Trim().EndsWith(" or")?a.coursetitle.Substring(0,a.coursetitle.Length-3):a.coursetitle } equals
new { subject = b.Subject, catalog = b.Catalogno, coursetitle = b.CourseTitle } into ab
from b in ab.DefaultIfEmpty()
where a.Active == true
select new JoinModel
{
Courses = a,
Summary2020 = b
} ).ToList();

Related

Retrieving Children from Multiple Parent Types, and Associating Them

What is the most efficient way to
a) retrieve all children objects from multiple parent types, and
b) know what the parent type is and the exact parent Id for each child?
Currently this is what I'm doing and it's incredibly inefficient, at least the part where I find the specific parent of each child.
public class ChildModel
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ParentType1Model
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ChildModel> Children { get; set; }
}
public class ParentType2Model
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ChildModel> Children { get; set; }
}
//Get all ChildModels from ParentType1
var parentType1Children = db.ParentType1Models
.SelectMany(x => x.Children)
.ToList();
listOfChildModels.AddRange(parentType1Children);
//Get all ChildModels from ParentType2
var parentType2Children = db.ParentType2Models
.SelectMany(x => x.Children)
.ToList();
listOfChildModels.AddRange(parentType2Children);
//Find the parent for each ChildModel
foreach (var child in listOfChildModels)
{
ParentType1Model parentType1ModelCheck = null;
ParentType2Model parentType2ModelCheck = null;
parentType1ModelCheck = await db.ParentType1Models
.Where(p => p.Children
.Any(i => i.Id == child.Id))
.FirstOrDefaultAsync();
//If first check is null, then move to second check
if (taskProjectModelCheck == null)
{
parentType2ModelCheck = await db.ParentType2Models
.Where(p => p.Children
.Any(i => i.Id == child.Id))
.FirstOrDefaultAsync();
}
//Now record the parent type and parent Id in an object containing the original ChildModel and it's parent's info (to be used later for various things)
ChildViewModel childViewModel = new ChildViewModel();
childViewModel.ChildModel = child;
if (parentType1ModelCheck != null)
{
childViewModel.ParentType = "ParentType1";
childViewModel.ParentModelId = parentType1ModelCheck.Id;
}
else if (parentType2ModelCheck != null)
{
childViewModel.ParentType = "ParentType2";
childViewModel.ParentModelId = parentType2ModelCheck.Id;
}
}
How about something like this?
var ids1 = from p in db.ParentType1Models
from c in p.Children
select new
{
parentId = p.Id,
parentName = p.Name,
childName = c.Name,
childId = c.Id,
ParentType = "One"
};
var ids2 = from p in db.ParentType2Models
from c in p.Children
select new
{
parentId = p.Id,
parentName = p.Name,
childName = c.Name,
childId = c.Id,
ParentType = "Two"
};
var results = ids1.Union(ids2).ToList();
I ended up using raw SQL, and it is extremely fast.
By writing a query directly against the database, I was able to go straight to the many to many relationship tables that get created by Entity Framework when I set up the ParentTypeXModels and ChildModels.
result = dbContext.Database.SqlQuery<ANewChildObject>(
"select
ParentModelId = pm.Id,
Id = c.Id,
ParentType = 'ParentType1'
from dbo.ChildModels c
JOIN dbo.ParentType1ModelsChildModels pmT ON c.Id = pmT.ChildModel_Id
JOIN dbo.ParentType1Models pm on pmT.ParentType1Model_Id = pm.Id
UNION ALL
select
ParentModelId = pm.Id,
Id = c.Id,
ParentType = 'ParentType2'
from dbo.ChildModels c
JOIN dbo.ParentType2ModelsChildModels pmT ON c.Id = pmT.ChildModel_Id
JOIN dbo.ParentType2Models pm on pmT.ParentType2Model_Id = pm.Id"
).ToList();

Json Data from datatable

Here i have a problem with data table to convert json. This is my class called SearchCollection
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public int ClassGroupId { get; set; }
public string ClassName { get; set; }
public int ClassNumber { get; set; }
public int BookTypeId { get; set; }
public string BookType { get; set; }
I have collected a data from store procedure and pushed into the datatable, thats why am using ConvertToDatatable(), that time i got a datatable which contains 3 tables data
static DataTable ConvertToDatatable(IEnumerable<SearchCollection> list)
{
var dt = new DataTable();
dt.Columns.Add("CategoryId");
dt.Columns.Add("CategoryName");
dt.Columns.Add("ClassGroupId");
dt.Columns.Add("ClassName");
dt.Columns.Add("ClassNumber");
dt.Columns.Add("BookTypeId");
dt.Columns.Add("BookType");
foreach (var item in list)
{
var row = dt.NewRow();
row["CategoryId"] = item.CategoryId;
row["CategoryName"] = item.CategoryName;
row["ClassGroupId"] = item.ClassGroupId;
row["ClassName"] = item.ClassName;
row["ClassNumber"] = item.ClassNumber;
row["BookTypeId"] = item.BookTypeId;
row["BookType"] = item.BookType;
dt.Rows.Add(row);
}
return dt;
}
this contain 3 tables data.
So.. this is have tried to group the data, but here am getting the answer like category on top inside category shows booktype and inside booktype shows list of classnames, but i want 3 set of data
category {},booktype{},classnames{}
var result = rows.GroupBy(r => new { x = r["CategoryId"], y = r["CategoryName"] }).Select(g => new
{
CategoryId = g.Key.x,
CategoryName = g.Key.y,
BookTypes = g.GroupBy(r => new { h = r["BookTypeId"], i = r["BookType"] }).Select(g1 => new
{
BookTypeId = g1.Key.h,
BookType = g1.Key.i,
ClassNames = g1.Select(r => new
{
ClassGroupId = r["ClassGroupId"],
ClassName = r["ClassName"],
ClassNumber = r["ClassNumber"]
}),
}),
});
Rusult
This is my result
{ CategoryId:1 CategoryName:CD ClassGroupId:15 ClassName:I ClassNumber:1 BookTypeId:1 BookType:General CD}
{ CategoryId:2 CategoryName:DVD ClassGroupId:16 ClassName:II ClassNumber:2 BookTypeId:2 BookType:General DVD}
{ CategoryId:3 CategoryName:Book ClassGroupId:17 ClassName:III ClassNumber:3 BookTypeId:3 BookType:General Books}
But i want the result like this
+ Category={ CategoryId:1 CategoryName:CD
CategoryId:2 CategoryName:DVD
CategoryId:3 CategoryName:Book }
ClassGroup={ClassGroupId:15 ClassName:I ClassNumber:1
ClassGroupId:16 ClassName:II ClassNumber:2
ClassGroupId:17 ClassName:III ClassNumber:3}
BookType{ BookTypeId:1 BookType:General CD
BookTypeId:2 BookType:General DVD
BookTypeId:3 BookType:General Books
}
here my result is booktype is under category and classname under booktype. but i want the result just like 3 groups of records in single json, any one help just like category grouped collection, class grouped collection and book type collection in single json data.
Is this what you're looking for?
var result = new
{
Category = rows
.GroupBy(r => new
{
x = r["CategoryId"],
y = r["CategoryName"]
})
.Select(g => new
{
CategoryId = g.Key.x,
CategoryName = g.Key.y
}),
ClassGroup = rows
.GroupBy(r => new
{
x = r["ClassGroupId"],
y = r["ClassName"],
z = r["ClassNumber"]
})
.Select(g => new
{
ClassGroupId = g.Key.x,
ClassName = g.Key.y,
ClassNumber = g.Key.z
}),
BookType = rows
.GroupBy(r => new
{
x = r["BookTypeId"],
y = r["BookType"]
})
.Select(g => new
{
BookTypeId = g.Key.x,
BookType = g.Key.y
})
};
Fiddle: https://dotnetfiddle.net/h9qXqc

How can I update related tables?

My project involves creating a new hotel room and 2 tables in my database will update. My tables are called RoomType and RoomFacility.
I can successfully update RoomType, but when I try to update RoomFacility and use RoomTypeID to make a new room facility, it fails. I always get 1 for my RoomFacilityID.
How can I update data for both tables, roomType and RoomFacility?
This is the code for my service to update my database
public void UpdateFacilityInRooms(List<int> FacilityIDs, int RoomTypeID)
{
List<HotelRoomFacility> hotelRoomFacilities =
_HotelRoomFacilityRopository.AsQueryable()
.Where(f => f.RoomTypeID == RoomTypeID).ToList();
foreach (int newRoomFacility in FacilityIDs)
{
if (hotelRoomFacilities.Where(h => h.RoomFacilityID == newRoomFacility).Count() == 0)
{
HotelRoomFacility facility = new HotelRoomFacility
{
RoomFacilityID = newRoomFacility,
RoomTypeID = RoomTypeID
};
_HotelRoomFacilityRopository.Add(facility);
}
}
_HotelRoomFacilityRopository.CommitChanges();
}
public RoomType NewRoom(int HotelID,int? RoomTypeID,
string RoomTypeName, string RoomTypeDescription)
{
RoomType room = new RoomType();
room.HotelID = HotelID;
room.RoomTypeID = RoomTypeID ?? 0;
room.RoomtypeName = RoomTypeName;
room.RoomTypeDescripton = RoomTypeDescription;
_RoomTypeRepository.Add(room);
_RoomTypeRepository.CommitChanges();
return room;
}
public RoomType UpdateRoom(int RoomTypeID, string RoomTypeName, string RoomTypeDescription, List<int> RoomFacilityIDs)
{
RoomType roomType = (from rt in _RoomTypeRepository.AsQueryable().Include(r => r.HotelRoomFacilities)
where rt.RoomTypeID == RoomTypeID
select rt).FirstOrDefault();
if (roomType == null)
return null;
roomType.RoomTypeName = RoomTypeName;
roomType.RoomTypeDescripton = RoomTypeDescription;
//Add New Room facilities
List<HotelRoomFacility> hotelRoomFacilities = _HotelRoomFacilityRopository.AsQueryable().Where(f => f.RoomTypeID == RoomTypeID).ToList();
foreach (int newRoomFacilityID in RoomFacilityIDs)
{
if (roomType.HotelRoomFacilities.Where(h => h.RoomFacilityID == newRoomFacilityID).Count() == 0)
{
roomType.HotelRoomFacilities.Add(new HotelRoomFacility
{
RoomFacilityID = newRoomFacilityID
});
}
}
foreach (HotelRoomFacility roomFacility in hotelRoomFacilities)
{
if (RoomFacilityIDs.Contains(roomFacility.RoomFacilityID) == false)
_HotelRoomFacilityRopository.Delete(roomFacility);
}
_RoomTypeRepository.Attach(roomType);
_RoomTypeRepository.CommitChanges();
return roomType;
}

How do you make an 'attendance table' for a classroom display with an appropriate layout?

I have been having a tough time getting an attendance table for a classroom to be displayed in an appropriate fashion. I have an Attendance table in my database that I can get to display quite easily with the data from just one classroom, but it displays in a way that looks like how it would look if you browsed to the attendance table directly in the database.
It is probably easier for me to explain by showing my work:
I have the following classes:
The actual classroom class, or Course:
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int AttendanceDate { get; set;}
public virtual ICollection<Enrollment> Enrollments { get; set; } // allows Students to be enrolled in a Course
etc. . .
}
My Students:
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; } // allows Student to be enrolled in a Course
etc. . .
}
The entity that ties the Students to the Courses:
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
Attendance data:
public class Attendance
{
public int AttendanceID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public int AttendanceDay { get; set; } // used to set how many days people are supposed to attend this Course (each course has a different length, some are 10 day courses, some are 3, etc.)
public bool Present { get; set; } // absent or present (set to absent by default)
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
The flow of my project has Instructors creating a Course for Students to sign up. When a Student signs up for a Course, all the necessary Attendance data is input into the Attendance database table with default values (absent every day):
for (int i = 0; i < course.AttendingDays; i++)
{
Attendance newAttendance = new Attendance
{
CourseID = course.CourseID,
StudentID = thisStudent.StudentID,
AttendanceDay = i + 1,
Present = false
};
db.Attendance.Add(newAttendance);
db.Save();
}
So I have a database table with a bunch of attendance data and I cannot get it to display correctly on the screen, sorted similar to this:
Attendance Day 1 | 2 | 3 | 4 | 5 |
Student1 absent absent absent absent absent
Student2 absent absent absent absent absent
Student3 absent absent absent absent absent
Hopefully you can read that. . . I assume it is a pretty standard layout for an attendance table.
I have tried sorting the data with Group By:
var model = from s in db.Attendance
where s.CourseID == 4
group s.AttendanceDay by s.StudentID into t
select new
{
StudentID = t.Key,
Days = t.OrderBy(x => x)
};
return View(model);
Which returns an IEnumerable of anonymous type (If I understand correctly), but I cannot seem to get this data to do anything. If I use 'simpler' table generators (and don't try to Group By the AttendanceDay number) I get the attendance table data just fine, but it is sorted just like it is when you view the actual database table for Attendance, not very useful if you want an Instructor to read and edit the information.
I am thinking I need an appropriate ViewModel to adjust the incoming attendance data in the IEnumerable of anonymous type format, followed by a view that appropriately displays that ViewModel. . . but I am not sure how I would handle that process.
Any help would be appreciated. Thank you.
Update:
I am beginning to think I need to take advantage of a "cross-tab report" / "pivoting" and use something like this: http://linqlib.codeplex.com/wikipage?title=Pivot&referringTitle=Home
Any pointers?
Update 2:
Almost completely solved using the below accepted answer, and here is my current controller:
// Generates list of Attendances specifically for current Course
var attendanceItems = db.Attendance.Where(s => s.CourseID == id);
List<Attendance> attendanceItemsList = attendanceItems.ToList();
// End of generating list of Attendances
// CURRENT PROBLEM AREA - INCOMPLETE
var student = attendanceItemsList.Select(a => a.Student).Distinct()/*.OrderBy(a => a)*/; // This works for adding one student, Cannot use OrderBy in its current state - how can I properly order by name? (right now it will order by id I believe)
List<Student> StudentList = student.ToList();;
//
// Generates list of AttendingDays specifically for current Course
Course course = db.Courses.FirstOrDefault(p => p.CourseID == id);
List<int> attDayList = new List<int>();
for (int i = 0; i < course.AttendingDays; i++)
{
attDayList.Add(i + 1);
};
// End of generating list of AttendingDays
AttendanceReportViewModel model = new AttendanceReportViewModel
{
AttendanceDays = attDayList,
Students = StudentList,
Attendances = attendanceItemsList,
};
return View(model);
I think you should look into creating a ViewModel that contains a list of days, a list of students, and a list of attendance entries, then simply iterate over the students and within it over the attendance days and then display the attendance record for each.
So the ViewModel would look something like this:
public class AttendanceReportViewModel
{
public List<int> AttendanceDays { get; set; }
public List<Student> Students { get; set; }
public List<Attendance> Attendances { get; set; }
public string IsPresent(Student student, int attendanceDay)
{
return Attendances.Single(a => a.StudentID == student.ID && a.AttendanceDay == attendanceDay).Present ? "present" : "absent";
}
}
Make sure to sort all items the way you would like them to appear, but this is simple OrderBy stuff. Also make sure to only load Attendance for the course in question and add any course data to the viewModel you want to show.
Then in your view iterate like so:
<table>
<thead>
<tr>
<th>Attendance Day</th>
#foreach (var attendanceDay in Model.AttendanceDays)
{
<th>#attendanceDay</th>
}
</tr>
<thead>
<tbody>
#foreach (var student in Model.Students)
{
<tr>
<td>#student.Name</td>
#foreach (var attendanceDay in Model.AttendanceDays)
{
<td>#Model.IsPresent(student, attendanceDay)</td>
}
</tr>
}
</tbody>
}
Just whacked this together for you, so not even sure if my exact code compiles, but I hope it gives you a good starting point. Obviously some styling to the table, etc. should be applied.
EDIT 1:
To load data into the view model you can just do this in the controller (ultimately this should technically speaking be in repositories and maybe even a service layer)
var viewModel = new AttendanceReportViewModel();
viewModel.AttendanceDays = db.Attendance.Select(a => a.AttendanceDay).Distinct().OrderBy(a => a)
...
I should also have noted that of course you could also only have loaded the attendance data only into the view model and then produced the AttendanceDays and Students properties in the ViewModel from this data. I avoided this for now as you would most likely want Student data as well.
EDIT 2
For students it is just more of the same you want all students enrolled in the class, but since you have initialized attendance data for all days up front you can just do this:
var viewModel = new AttendanceReportViewModel();
viewModel.AttendanceDays = db.Attendance.Select(a => a.AttendanceDay).Distinct().OrderBy(a => a);
viewModel.Students = db.Attendance.Select(a => a.Student).Distinct().OrderBy(s => s.Name);
Alternatively you can just load this information from the Enrollment table like so:
viewModel.Students = db.Enrollment.Where(e => e.CourseID == courseID).Select(e => e.Student).OrderBy(s => s.Name);
Please note that I presume that there is a unique constraint between course and student id on the enrollment table and that courseID is what you produce the attendance report for. Also you have Course in your Enrollment table mapped to Student above, which I would assume is incorrect.
CREATE PROCEDURE [dbo].[SP_S_GetDaywise_EmpTotalDuties_AttendanceRegister]
(
#Month int=null,
#Year int=null,
#SCode bigint=null
)
AS
/**Creating TempAllAttendance**/
CREATE TABLE #TempAllAttendance
(RecId bigint IDENTITY(1,1),EmpCode BIGINT,Duties FLOAT,AttDay INT, DESIGNATION NVARCHAR(250))
/**Creating TempAllAttendance**/
/**Creating SumAttendance**/
CREATE TABLE #SumAttendance
(Total FLOAT)
/**Creating SumAttendance**/
DECLARE #TotalDuties FLOAT=null
BEGIN
SET #TotalDuties=(SELECT SUM(ISNULL(Duties, 0)) AS Total FROM tbl_Attendance WHERE ([Month] = #Month) AND ([Year] = #Year) AND (SCode = #SCode))
INSERT INTO #SumAttendance
(Total)VALUES(#TotalDuties)
INSERT INTO #TempAllAttendance(EmpCode,Duties,AttDay,DESIGNATION)
(
SELECT EmpCode, SUM(ISNULL(Duty1, 0)) AS Duties, DAY(AttendanceDate) AS AttDay,DESIGNATION
FROM tbl_Attendance
WHERE ([Month] = #Month) AND ([Year] = #Year) AND (SCode = #Code)
GROUP BY EmpCode, AttendanceDate,DESIGNATION
)
/**This is used to get date wise & Swise Total duty When Records Not Saved In tbl_SiteWiseEmployee_TotalAttendance**/
/**This is used to get date wise & Sise Total duty When Records Saved In tbl_SiteWiseEmployee_TotalAttendance**/
/**This is used to get date wise & Swise Total duty**/
SELECT * FROM #TempAllAttendance
/**This is used to get date wise & Sitewise Total duty**/
/**This is used to get date wise Total duty**/
SELECT EmpCode,SUM(ISNULL(Duties, 0)) AS Duties,AttDay,DESIGNATION FROM #TempAllAttendance
GROUP BY EmpCode, AttDay,EmpCode,DESIGNATION
/**This is used to get Employee SumAttendance**/
SELECT SUM(Duties) AS Duties,DAY(AttendanceDate) AS AttDay FROM tbl_Attendance
WHERE (SiteCode = #SCode) AND ([Month] = #Month) AND ([Year] = #Year) GROUP BY AttendanceDate
/**This is used to get Employee SumAttendance**/
SELECT * FROM #SumAttendance
/**This is used to get date wise & Sitewise Total duty AS P**/
--SELECT RecId,EmpCode,'P' AS Duties,AttDay FROM #TempAllAttendance
SELECT EmpCode,'P' AS Duties,AttDay FROM #TempAllAttendance
GROUP BY EmpCode, AttDay
/**This is used to get date wise & Swise Total duty AS P**/
DROP TABLE #SumAttendance
DROP TABLE #TempAllAttendance
END
private void STotalEmployeeAttendenceReportAsDuty()
{
#region For Displaying page Header region
lblMonthId.Value = Request.QueryString["Month"];
lblMonthName.Value = Request.QueryString["MonthName"];
lblYear.Value = Request.QueryString["year"];
lblSCode.Value = Request.QueryString["SCode"];
lblgvSName.Value = Request.QueryString["SName"];
lblMonth.InnerText = lblMonthName.Value;
lblYears.InnerText = lblYear.Value;
lblSName.InnerText = lblgvSiName.Value + "-" + lblSCode.Value;
#endregion
#region Get SWise Employee Detail
siAttndncPL.SiteCode = lblSiteCode.Value;
sAttndncPL.Month = lblMonthId.Value;
siAttndncPL.Year = lblYear.Value;
DataTable EmpDt = siteAttndncBL.GetEmployeeNameWithTotalDutiesBySit(siteAttndncPL);
#endregion
#region Making TempTable.
DataTable dt = new DataTable();
DataColumn dc = new DataColumn();
dc.ColumnName = "EmpCode";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "EmpName";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "Designation";
dt.Columns.Add(dc);
/**Some Table**/
DataTable dtdayDuties = new DataTable();
DataTable dtEmpDayDuties = new DataTable();
DataTable dtEmpDutiesAsP = new DataTable();
DataTable dtSumDuty = new DataTable();
/**Some Region**/
#endregion
#region Get No Of Days In Month..
int DaysCount = DateTime.DaysInMonth(Convert.ToInt32(Request.QueryString["Year"]), Convert.ToInt32(Request.QueryString["Month"]));
#endregion
#region This will dispaly date value on grid header
for (int i = 1; i <= 9; i++)
{
dc = new DataColumn();
dc.ColumnName = "0" + i.ToString();
dt.Columns.Add(dc);
}
for (int i = 10; i <= DaysCount; i++)
{
dc = new DataColumn();
dc.ColumnName = i.ToString();
dt.Columns.Add(dc);
}
dc = new DataColumn();
dc.ColumnName = "Total";
dt.Columns.Add(dc);
#endregion
#region /*Adding Site Name Row in Grid View*/
for (int j = 0; j < EmpDt.Rows.Count + 1; j++)
{
DataRow dtrow = dt.NewRow();
if (j < EmpDt.Rows.Count)
{
dtrow[0] = EmpDt.Rows[j][0];/**this Row Cells EmpCode**/
string EmpCode = EmpDt.Rows[j][0].ToString();
// lblEmpCode = EmpDt.Rows[j][0].ToString();
dtrow[1] = EmpDt.Rows[j][1];/**this Row Cells EmpName**/
dtrow[2] = EmpDt.Rows[j][2];/**this Row Cells DESsgName**/
dtrow[DaysCount + 3] = EmpDt.Rows[j][3];/**this Row Cells Duties **/
#region Get EmployeeWise Total Duties.
siteAttndncPL.SiteCode = lblSiteCode.Value;
siteAttndncPL.Month = lblMonthId.Value;
siteAttndncPL.Year = lblYear.Value;
DataSet ds = siteAttndncBL.GetEmployeeDayWiseAttendenceBySCode_WOPHD(siteAttndncPL);
dtEmpDutiesAsP = ds.Tables["tbl_GetEmpTotalAttendanceOfDayAsP"];/*getting Site Duties as P*/
dtEmpDayDuties = ds.Tables["tbl_GetEmpTotalAttendanceOfDay"];
dtdayDuties = ds.Tables["tbl_SumOfAllEmpDayWiseDuties"];
dtSumDuty = ds.Tables["tbl_TotalSumOfAllEmpAttendance"];
TotalSumDuties = Convert.ToDouble(dtSumDuty.Rows[0]["Total"].ToString());
#endregion
}
if (j == EmpDt.Rows.Count)
{
#region Count Total Duties.
dtrow[2] = "Total Duties";
dtrow[DaysCount + 3] = TotalSumDuties;/**Sum Of All Main Attendance**/
#endregion
}
dt.Rows.Add(dtrow);
}
#endregion
/**Fill Day Wise Attendance In Gridview**/
#region Day Wise Attendance fill In Gridview..
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i < dt.Rows.Count - 1)
{
for (int j = 3; j < dt.Columns.Count; j++)
{
foreach (DataRow dtrows in dtEmpDayDuties.Rows)
{
/*Matching Emp Code*/
if (dt.Rows[i][0].ToString() == dtrows[0].ToString())
{
/*Matching Emp Category */
if (dt.Rows[i][2].ToString() == dtrows[3].ToString())
{
TextBox txtDuty = new TextBox();
txtDuty.Text = dt.Columns[j].ColumnName.ToString();
txtDuty.Text = dtrows[2].ToString();
/*Matching Date*/
if (Convert.ToString(j - 2) == dtrows[2].ToString())
{
dt.Rows[i][j] = dtrows[1].ToString(); /*Filling Days wise duty*/
}
}
/*Matching Emp Category */
}
}
}
}
if (i == dt.Rows.Count - 1)
{
for (int j = 3; j < dt.Columns.Count; j++)
{
foreach (DataRow dtrows in dtdayDuties.Rows)
{
TextBox txtDuty = new TextBox();
txtDuty.Text = dt.Columns[j].ColumnName.ToString();
txtDuty.Text = dtrows[1].ToString();
if (Convert.ToString(j - 2) == dtrows[1].ToString())
{
dt.Rows[i][j] = dtrows[0].ToString();
}
}
}
}
}
#endregion
/**Fill Day Wise Attendance In Gridview**/
#region Binding Grid
grdSWiseEmpAttendance.DataSource = dt;
grdSWiseEmpAttendance.DataBind();
#endregion Binding Grid
ViewState["tbldata"] = dt;/*used For Saving Employee Monthly Attendance*/
Session["reportdata"] = dt;/*used For Printing Employee Monthly Attendance*/
lblNoOfEmp.InnerText = (grdSWiseEmpAttendance.Rows.Count - 1).ToString();
}
void Page_Init(object obj, EventArgs e)
{
int days = DateTime.DaysInMonth(Convert.ToInt32(Request.QueryString["Year"]), Convert.ToInt32(Request.QueryString["Month"]));
int dtinc = 0;
for (int rowcnt = 0; rowcnt < days + 4; rowcnt++)
{
if (rowcnt == 0)
{
BoundField nameColumn = new BoundField();
nameColumn.DataField = "EmpCode";
nameColumn.HeaderText = "EmpCode";
grdSiteWiseEmpAttendance.Columns.Add(nameColumn);
}
else if (rowcnt == 1)
{
BoundField nameColumn = new BoundField();
nameColumn.DataField = "EmpName";
nameColumn.HeaderText = "EmpName";
grdSiteWiseEmpAttendance.Columns.Add(nameColumn);
}
else if (rowcnt == 2)
{
BoundField nameColumn = new BoundField();
nameColumn.DataField = "DESIGNATION";
nameColumn.HeaderText = "DESIGNATION";
grdSiteWiseEmpAttendance.Columns.Add(nameColumn);
}
else if (rowcnt == days + 3)
{
BoundField nameColumn = new BoundField();
nameColumn.DataField = "Total";
nameColumn.HeaderText = "Total";
grdSiteWiseEmpAttendance.Columns.Add(nameColumn);
nameColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
}
else
{
dtinc = dtinc + 1;
string formet = "00";
TemplateField bfield = new TemplateField();
/**Initalize the DataField value**/
bfield.HeaderTemplate = new GridViewTemplate2(ListItemType.Header, Convert.ToString(dtinc.ToString(formet)));
/**Initialize the HeaderText field value**/
bfield.ItemTemplate = new GridViewTemplate2(ListItemType.Item, Convert.ToString(dtinc.ToString(formet)));
/**Add the newly created bound field to the GridView**/
grdSEmpAttendance.Columns.Add(bfield);
}
}
}
<div class="row">
<div class="col-lg-12">
<div class="table-responsive">
<asp:GridView ID="grdSiEmpAttendance" CssClass="table table-small-font table-bordered table-striped" Font-Size="Smaller" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="10" HeaderStyle-Font-Names="Arial" HeaderStyle-Font-Italic="true" runat="server" AutoGenerateColumns="false"
BackColor="#f0f5f5" HeaderStyle-ForeColor="#990000">
<Columns>
</Columns>
<HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top"
Font-Bold="true" />
<RowStyle Font-Size="Small" Height="1" ForeColor="#000000" Font-Italic="true" />
</asp:GridView>
</div>
</div>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
public class GridViewTemplate2 : ITemplate
{
/**A variable to hold the type of ListItemType**/
ListItemType _templateType;
/**A variable to hold the column name**/
string _columnName;
/**Constructor where we define the template type and column Name**/
public GridViewTemplate2(ListItemType type, string colname)
{
_templateType = type; /*Stores the template type*/
_columnName = colname;/*Stores the column name*/
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
#region For Use TemplateFields.
case ListItemType.Header:
/*Create a New Label control and add it to the container*/
Label lbl = new Label();/*Allocates the new label object*/
lbl.Text = _columnName;/*Assigns the name of the column in the lable*/
lbl.Font.Name = "Calibri";
//lbl.CssClass = "form-label";
//lbl.Font.Bold = true;
container.Controls.Add(lbl);/*Adds the New created label control to the container*/
break;
case ListItemType.Item:
/**Creates a New Text box Control And Add It to the container**/
TextBox tb1 = new TextBox();/*Allocates the new text box object*/
tb1.DataBinding += new EventHandler(tb1_DataBinding);/*Attaches the data binding event*/
tb1.CssClass = "vertical-text";
string bxid = "txt" + _columnName;
tb1.ID = bxid.Trim().ToString();
tb1.Width = new Unit(35, UnitType.Pixel);
tb1.Height = new Unit(15, UnitType.Pixel);
//tb1.Style.Add("font-size", "8pt;");
tb1.Font.Name = "Calibri";
tb1.Columns = 3; /**Creates a column with size 4**/
container.Controls.Add(tb1);/**Adds the New created textbox to the container**/
break;
case ListItemType.EditItem:
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
#endregion
}
}
/// <summary>
/// This is the event, which will be raised when the binding happens.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
///
void tb1_DataBinding(object sender, EventArgs e)
{
#region For Use DataBinding Fields..
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
if (dataValue.ToString().Trim() == "0".ToString() || dataValue.ToString().Trim()=="")
{
txtdata.Text = "";
//txtdata.BackColor = System.Drawing.Color.BlanchedAlmond;
//txtdata.ReadOnly = true;
txtdata.Width = 35;
txtdata.Height = 25;
txtdata.CssClass = "form-control input-sm m-bot15";
txtdata.Font.Size = 8;
}
if (dataValue.ToString().Trim() == "777" || dataValue.ToString().Trim() == "L")
{
txtdata.Text = "L";
txtdata.BackColor = System.Drawing.Color.SandyBrown;
//txtdata.ReadOnly = true;
txtdata.Width = 35;
txtdata.Height = 25;
txtdata.CssClass = "form-control input-sm m-bot15";
txtdata.Font.Size = 7;
}
if (dataValue.ToString().Trim() == "888" || dataValue.ToString().Trim() == "WO")
{
txtdata.Text = "WO";
txtdata.BackColor = System.Drawing.Color.LightGreen;
//txtdata.ReadOnly = true;
txtdata.Width = 36;
txtdata.Height = 25;
txtdata.CssClass = "form-control input-sm m-bot15";
txtdata.Font.Size = 7;
}
if (dataValue.ToString().Trim() == "999" || dataValue.ToString().Trim() == "PH")
{
txtdata.Text = "PH";
txtdata.BackColor = System.Drawing.Color.Cornsilk;
//txtdata.ReadOnly = true;
txtdata.Width = 35;
txtdata.Height = 25;
txtdata.CssClass = "form-control input-sm m-bot15";
txtdata.Font.Size = 7;
}
if (dataValue.ToString().Trim() == "1111" || dataValue.ToString().Trim() == "CL")
{
txtdata.Text = "CL";
txtdata.BackColor = System.Drawing.Color.Bisque;
//txtdata.ReadOnly = true;
txtdata.Width = 35;
txtdata.Height = 25;
txtdata.CssClass = "form-control input-sm m-bot15";
txtdata.Font.Size = 7;
}
if ((dataValue.ToString().Trim() != "1111") && (dataValue.ToString().Trim() != "CL") && (dataValue.ToString().Trim() != "2997") && (dataValue.ToString().Trim() != "HD") && (dataValue.ToString().Trim() != "777") && (dataValue.ToString().Trim() != "L") && (dataValue.ToString().Trim() != "888") && (dataValue.ToString().Trim() != "W/O") (dataValue.ToString().Trim() != "") && (dataValue.ToString().Trim() != "1")&&
{
txtdata.ReadOnly = false;
txtdata.BackColor = System.Drawing.Color.LightGoldenrodYellow;
txtdata.Text = dataValue.ToString();
txtdata.Width = 35;
txtdata.Height = 25;
txtdata.CssClass = "form-control input-sm m-bot15";
txtdata.Font.Size = 7;
txtdata.Font.Bold = true;
}
if ((dataValue.ToString().Trim() != "1111") && (dataValue.ToString().Trim() != "CL") && (dataValue.ToString().Trim() != "2997") && (dataValue.ToString().Trim() != "HD") && (dataValue.ToString().Trim() != "777") && (dataValue.ToString().Trim() != "L") && (dataValue.ToString().Trim() != "888") && (dataValue.ToString().Trim() != "WO") && (dataValue.ToString().Trim() != "1776") && (dataValue.ToString().Trim() != "") && (dataValue.ToString().Trim() != "3000") && (dataValue.ToString().Trim() != "T") && (dataValue.ToString().Trim() != "1000") &&
{
txtdata.ReadOnly = false;
txtdata.Text = dataValue.ToString();
txtdata.Width = 35;
txtdata.Height = 25;
txtdata.CssClass = "form-control input-sm m-bot15";
txtdata.Font.Size = 7;
txtdata.Font.Bold = true;
}
//else
//{
// txtdata.ReadOnly = false;
// txtdata.Text = dataValue.ToString();
// txtdata.Width = 35;
// txtdata.Height = 25;
// txtdata.CssClass = "form-control input-sm m-bot15";
// txtdata.Font.Size = 8;
// txtdata.Font.Bold = true;
//}
}
else
{
txtdata.Text ="";
txtdata.Width = 35;
txtdata.Height = 25;
txtdata.CssClass = "form-control input-sm m-bot15";
txtdata.Font.Size = 8;
txtdata.Font.Bold = true;
}
#endregion
}
}

What does this model error says in asp.net mvc?

My Html action link takes me to a view where i can see the details..
For Ex:http://localhost:1985/Materials/Details/4
But it shows error,
The model item passed into the dictionary is of type
'System.Data.Linq.DataQuery`1[CrMVC.Models.ConstructionRepository+Materials]'
but this dictionary requires a model item of type
'CrMVC.Models.ConstructionRepository+Materials'.
And my model is...
public IQueryable<Materials> GetMaterial(int id)
{
return from m in db.Materials
join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id
where m.Mat_id == id
select new Materials()
{
Id = Convert.ToInt64(m.Mat_id),
Mat_Name = m.Mat_Name,
Mes_Name = Mt.Name,
};
}
public class Materials
{
private Int64 id;
public string mat_Name;
public string mes_Name;
public Int64 Id
{
get
{
return id;
}
set
{
id = value;
}
}
public string Mat_Name
{
get
{
return mat_Name;
}
set
{
mat_Name = value;
}
}
public string Mes_Name
{
get
{
return mes_Name;
}
set
{
mes_Name = value;
}
}
}
}
and my controller method...
public ActionResult Details(int id)
{
var material = consRepository.GetMaterial(id).AsQueryable();
return View("Details", material);
}
Any suggestion what am i missing here?
Your GetMaterial(id) method should probably return just one Material instance because your View expects just one instance. E.g:
public Materials GetMaterial(int id)
{
return (from m in db.Materials
join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id
where m.Mat_id == id
select new Materials()
{
Id = Convert.ToInt64(m.Mat_id),
Mat_Name = m.Mat_Name,
Mes_Name = Mt.Name,
}).FirstOrDefault();
}

Resources