I'm trying to display linq results into a view but I have not been able to. The error I get is "The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType22[System.Double,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable"
I created my view manually and by right clicking the controller and adding a view but I'm kind of stuck here.
public ActionResult leftjoin()
{
var q = from b in db.OrderHistories
join c in db.BuyerComms on b.ITEMID equals c.ITEMID into sr
from x in sr.DefaultIfEmpty()
select new { Item = b.ITEMID, buyer = x.Buyer };
return View (q.ToList());
}
and my view:
#model IEnumerable<myapp.Models.OrderHistory>
I used linqpad to test my linq and I'm getting the right results.
Your query is returning an anonymous type as indicated by:
select new { Item = b.ITEMID, buyer = x.Buyer };
You need to instead select into a type of OrderHistory. You didn't provide that class, so I'm going to guess that it's something like:
select new OrderHistory { Item = b.ITEMID, buyer = x.Buyer };
Related
I am trying to convert anonymous types to list but i am getting invocation errors like below.
An unhandled exception of type
'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
var all = from a in Fcticuclist
join b in crlist on a.Ref_CID equals b.C_ID
select new { b.MU_Identifier, a.Status,a.ID };
foreach (var item in all)
{
castapprove.Add(new muapprovelist { Id = item.ID, MU_Identifier = item.MU_Identifier, Status = item.Status });
}
so here "all" is anonymous type and castapprove is a list and muapprovelist is a class and they are declared in the same view model. Any pointers where i am doing it wrong ?
Presumably this is some accessibility issue relating to dynamic compilation of a view of some kind and the anonymous type (which is internal). Perhaps a pragmatic solution is to not use the anonymous type in this case:
var all = from a in Fcticuclist
join b in crlist on a.Ref_CID equals b.C_ID
select new muapprovelist {
Id = a.ID, MU_Identifier = b.MU_Identifier,
Status = a.Status };
foreach (var item in all)
{
castapprove.Add(item);
}
Perhaps even:
var castapprove = (from a in Fcticuclist
join b in crlist on a.Ref_CID equals b.C_ID
select new muapprovelist {
Id = a.ID, MU_Identifier = b.MU_Identifier,
Status = a.Status }).ToList();
Alternatively: move this code away from the view area into code that is part of the main pre-compiled assembly.
i want to print the viewbag recieved from the controller but i cant, my code in the controller is here:
var qry = from c in db.Customers
join o in db.Orders on id equals o.CustomerID
where id == o.CustomerID
select new {o.OrderID ,o.OrderDetails};
ViewBag.OrdersForUser = qry.ToList();
the printing code in my view is :
#foreach (var order in ViewBag.OrdersForUser)
{
#order
}
the printed text right now is:
{ OrderID = 1, OrderDetails = System.Collections.Generic.HashSet`1[FinalProject.Models.OrderDetail] }
the type of OrderID is int, the type of OrderDeatils is ICollection
i want to print the data in the hash set (and not the decleration like now) , and to split the Order Id into other space.
ViewBag is a dynamic type. And you assign an anonymous type, then you cant get its type in view side.
controller
var qry = from c in db.Customers
join o in db.Orders on id equals o.CustomerID
where id == o.CustomerID
// in this line, what is the type of list ? You should define its type
// for example:
select new SomeType{OrderId = o.OrderID ,OrderDetails = o.OrderDetails}
//select new {o.OrderID ,o.OrderDetails};
ViewBag.OrdersForUser = qry.ToList();
and then in your
view
#foreach (var order in (List<SomeType>)ViewBag.OrdersForUser)
{
#order
}
List that you return from controller, should not be anonymous type. (select new SomeType)
In view, you should define viewbag type. (List)ViewBag.OrdersForUser)
AFTER COMMENT
Or if there is relation definitions between your entities, you can get only order details like following :
controller:
ViewBag.OrdersForUser = db.OrderDetails.Where(d=>d.Order.CustomerId == id);
view :
#foreach (var orderDetail in (List<OrderDetail>)ViewBag.OrdersForUser)
{
#orderDetail.Order.xxx
}
I have LINQ output which I am trying to pass in list but I am getting following error
in linq result I am trying to pass data from two class model, if I do one class model (listOfCoursesWithoutURL ) then it work but I need to pass processedCourseInstance. I have created ModelView of two classes but not sure what I am missing in this picture
ViewModel
public class CoursesInstanceStudyLevel_ViewModel
{
public CourseInstanceModel _CourseInstanceModel { get; set; }
public StudyLevelModel _StudyLevelModel { get; set; }
}
My Class
public List<CoursesInstanceStudyLevel_ViewModel> ProcessAllCoursesApplicationURL(CourseApplicationsURLFeed_Model _obj)
{
using(var _uof = new Courses_UnitOfWork())
{
_uof.CourseInstances_Repository.GetAll();
var _listOfCoursesWithoutURL = (from b in ListOfCoursesInstances
where b.ApplicationURL == null
select b).ToList();
var processedCourseInstance = (from _courseInstances in _uof.CourseInstances_Repository.GetAll()
join _courses in _uof.Courses_Repository.GetAll() on _courseInstances.CourseID equals _courses.CourseID
join _studylevel in _uof.StudyLevel_Repository.GetAll() on _courses.StudyLevelId equals _studylevel.StudyLevelID
orderby _courseInstances.CourseCode
select new { _courseInstances, _studylevel }).ToList();
return processedCourseInstance; // it doesn't work ... refer to screen shot
// return _listOfCoursesWithoutURL //it works
}
}
Error
here:
select new { _courseInstances, _studylevel })
you are defining an anonymous object. You have a type ready, so use that one:
select new CoursesInstanceStudyLevel_ViewModel
{
_CourseInstanceModel = _courseInstances,
_StudyLevelModel = _studylevel
}
assuming CourseInstanceModel and StudyLevelModel are the correct types
With highlighted line in following code snippet, you are selecting an anonymous object instead of a concrete CourseIntaceStudyLeve_ViewModel
select new { _courseInstances, _studylevel }
You will have to change your query to following..
var processedCourseInstance = (from _courseInstances in _uof.CourseInstances_Repository.GetAll()
join _courses in _uof.Courses_Repository.GetAll() on _courseInstances.CourseID equals _courses.CourseID
join _studylevel in _uof.StudyLevel_Repository.GetAll() on _courses.StudyLevelId equals _studylevel.StudyLevelID
orderby _courseInstances.CourseCode
select new CoursesInstanceStudyLevel_ViewModel(){
_CourseInstanceModel = _courseInstances.FirstOrDefault(),
StudyLevelModel = _studylevel.FirstOrDefault()}).ToList();
I have assumed you would need only first course and first study level based on your view model definition and there for applied FirstOrDefault. You can choose to go along with this or change your view model definition.
here is my answer and it works
var processedCourseInstance =
(from _courseInstances in _uof.CourseInstances_Repository.GetAll()
join _courses in _uof.Courses_Repository.GetAll() on _courseInstances.CourseID equals _courses.CourseID
join _studylevel in _uof.StudyLevel_Repository.GetAll() on _courses.StudyLevelId equals _studylevel.StudyLevelID
orderby _courseInstances.CourseCode
select new CoursesInstanceStudyLevel_ViewModel() {
_CourseInstanceModel = _courseInstances,
_StudyLevelModel = _studylevel
}).ToList();
Im getting an error in my C# project which is causing me a headache. The error is:
Cannot implicitly convert type 'System.Collecitons.Generic.IEnumbrable<Models.tbl_station>'
to Models.tbl_station An explicit conversion exists(are u missing a cast)
Here is my code.
var results =
(from p in db.tbl_pageDetail
group p by new { p.station_id, p.category_id } into g
let pageno = (from i in g select i.pageNo)
let station = (from i in g select i.tbl_station)
select new
{
g.Key.category_id,
g.Key.station_id,
pageno,
station
}).ToList();
var data =
results.Select(x =>
new tbl_pageDetail
{
category_id = x.category_id,
pageNo = string.Join(", ", x.pageno),
station_id = x.station_id,
tbl_station = x.station // Here i getting error
});
return View(data);
Your error message is self explanatory! x.station is an IEnumerable and you are trying to store that in tbl_station. Just consider your own example:-
pageNo = string.Join(", ", x.pageno)
Here since x.pageno was an IEnumerable you were able to pass it to Join method to create a single item, Same is the case with tbl_station = x.station, here you have a List so you cannot store that into a single object, you either need an IEnumerable of tbl_station or you need to fetch a single item from x.station by using FirstOrDefault() or SingleOrDefault().
I have 2 Databases using EF w/ MVC4. I have searched all through SO to avail. I need to return a list of Alerts to a partial view. However the Alerts should be filtered by a specific username with a specific identifier. The View is strongly typed, and I'd like to keep it like that.
I have the LINQ query returning to a List and it's the list of the usernames associated with the specific id. You can see in the second case statement where the two table lookup needs to go.I want to do this without a viewmodel class.
Here is the code:
public PartialViewResult DashboardAlerts()
{
Database.SetInitializer<AlertsContext>(null);
AlertsContext db = new AlertsContext();
Database.SetInitializer<MemberUsersContext>(null);
MemberUsersContext mdb = new MemberUsersContext();
var members = new List<MemberUsers>(mdb.MemberUsers);
var alerts = new List<Alerts>(db.Alerts);
var query = from x in alerts
join y in members
on x.username equals y.username
where y.clubID == (int)Session["ClubID"]
select new { username = y.username};
var list = query.ToList();
switch (Session["RoleName"].ToString())
{
case "GMC Admin": return PartialView(db.Alerts.ToList());
case "Club Admin": return //return db.Alerts.ToList() that has only usernames from query.ToList();
default: return PartialView(db.Alerts.Where(x => x.username == User.Identity.Name).ToList());
}
}
Bottom Line: I want to cross reference db.Alerts with only values from query list's username property.
From your question, you use want to narrow down the alerts to the ones where you have the usename in query. looks like you already have that done, just dont select the username, but the alert instead
var query = from x in alerts
join y in members
on x.username equals y.username
where y.clubID == (int)Session["ClubID"]
select x;
that will return you the alerts rather than the list of usernames.