Viewbag , Printing data from hashset - c#

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
}

Related

LINQ select new model without need of typing every parameter

is it possible in LINQ to get all properties from two tables into new ViewModel without listing PersonId, Email and so on.
var person = (from o in db.Persons
join od in db.OsobeDetails on o.PersonId equals od.PersonId
where o.PersonId == id
select new PersonViewModel
{
PersonId= o.PersonId,
Email = o.Email
}).ToList();
something like:
... select new PersonViewModel();
I tried this but I don't get any results back. "id" is input parameter into method.
You could have an override of your PersonViewModel constructor that takes a Person object, and set the properties there.
For example, if you had this constructor:
class PersonViewModel
{
public PersonViewModel(Person person)
{
this.PersonId = person.PersonId;
this.Email = person.Email;
// ... other properties set here
}
}
Then you could just do:
var person = (from person in db.Persons
join od in db.OsobeDetails
on person.PersonId equals od.PersonId
where person.PersonId == id
select new PersonViewModel(person))
.ToList();
This returns both entities o and od:
var person = (from o in db.Persons
join od in db.OsobeDetails on o.PersonId equals od.PersonId
where o.PersonId == id
select new { Persons = o, OsebeDetails = od }).ToList();
access it something like:
person.Persons.PersonID
or
person.OsebeDetails.PersonID
or any other existing property.

returning multiple class model data from linq in list via return method in C#

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();

ASP.Net MVC 5 Entity Framework Select Where In?

I have 3 tables Project, Province, ProjProvRel
In my project page when I add data I select multiple provinces for each project
means my Province is multi select dropdown list.
I insert data it is working I get the inserted Id and added to ProjProvRel with selected Ids of Province
Now In details view I want to display my data but I could not solve it.
here is my code:
// GET: Project/Details/5
public ActionResult Details(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var mydata = db.Projects.Find(id);
if (mydata == null)
{
return HttpNotFound();
}
var prov_id = from o in db.ProRel where o.ProjectId.Equals(id) select o.ProvinceIds;
foreach (var p_id in prov_id)
{
int[] PIds = new int[] {p_id};
}
var Prov= from c in db.Provinces where c.ID in pIds;
ViewBag.Province = Prov;
return View(mydata);
}
one problem is how can I select data from table based on where condition
var prov_id = from o in db.ProRel where o.ProjectId.Equals(id) select o.ProvinceIds;
is the above query correct ? I am new to ASP.Net MVC
also blow query is correct ?
var Prov= from c in db.Provinces where c.ID in pIds;
how can I select data from Table Province where province.ID in PIds
Get the rows from ProRel where the ProjectId matches with id:
var prov_ids = db.ProRel.Where(r => r.ProjectId == id).Select(r => r.ProvinceId);
Get the provinces that can be found from prov_id:
var provs = db.Provinces.Where(p => prov_id.Any(i => p.ID == i));
I hope you don't mind the lambda-style LINQ.
Also, I think you should consider your variable naming. For example, prov_id gives the idea of a single id and since you declared the type implicitly it is difficult to tell otherwise.

MVC Unable to display Linq query result to view

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 };

Get list of child records

I have a database that looks like this:
tbl_Seminar
ID
isActive
tbl_SeminarFees
ID
seminar_id -- foreign key
fee_text
I want to get all seminars that are active (isActive ==1) and a list of the fees associated with that seminar. Each Seminar may have n records in tbl_SeminarFees that are its fees. I am able to return a linq structure that returns me a list of objects that look like this {seminar, SeminarFee} but I wanted to create a nested structure that looks like this:
{seminar, List<SeminarFee>}
What should my linq query look like?
here is my linq currently:
var results = from s in context.Seminar
join p in context.SeminarFees on
s.ID equals p.SeminarID
where s.IsActive == 1
select new
{
Seminar = s,
Fees = p
};
How do I change this to get a list of these: {seminar, List<SeminarFee>}
Thanks
UPDATE
#lazyberezovsky gave me a good idea to use a group join and into another variable. But then how do I loop through the result set. Here is what I have now:
foreach (var seminarAndItsFeesObject in results)
{
//do something with the seminar object
//do something with the list of fees
}
This however gives me the following error:
Argument type 'SeminarFees' does not match the
corresponding member type
'System.Collections.Generic.IEnumerable`1[SeminarFees]'
What am I doing wrong?
Thanks
You can use group join which groups inner sequence items based on keys equality (a.k.a. join..into) to get all fees related to seminar:
var results = from s in context.Seminar
join f in context.SeminarFees on
s.ID equals f.SeminarID into fees // here
where s.IsActive == 1
select new
{
Seminar = s,
Fees = fees
};
You can't call ToList() on server side. But you can map results on client later.
BTW You can define navigation property Fees on Seminar object:
public virtual ICollection<SeminarFee> Fees { get; set; }
In this case you will be able load seminars with fees:
var results = context.Seminar.Include(s => s.Fees) // eager loading
.Where(s => s.IsActive == 1);
var results = from s in context.Seminar
join p in context.SeminarFees on s.ID equals p.SeminarID
where s.IsActive == 1
group p by s into grouped
select new {
Seminar = grouped.Key,
Fees = grouped.ToList()
};

Categories