Populate a view model with a data model with a method aswell - c#

i need to populate my articles ViewModel with a model that has the database data in it, but i have a method that i need to assign to one of my properties
The list of images is the property that needs the method on it.
The method is called once for every item in the list of articles.
Here is my code:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
}).ToList();
articleViewModel.Images = imageService.GetImagesForArticle(articlemodel.Id.ToString());
return View(query);
}
I have also tried putting the method inside the linq:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var query = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName,
Images = imageService.GetImagesForArticle(a.Id.ToString())
}).ToList();
return View(query);
}
it throws an exception of:
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[New_MinecraftNews_Webiste_MVC.Models.ImageInfo] GetImagesForArticle

I added a foreach loop at the end insted of anything else and it works:
public ActionResult ArticleTypes(string at)
{
articleViewModel.Images = new List<ImageInfo>();
var modelList = (from a in db.Articles
where a.SelectedArticleType == at
select new ArticlesViewModel
{
Id = a.Id,
Body = a.Body,
Headline = a.Headline,
PostedDate = a.PostedDate,
SelectedArticleType = a.SelectedArticleType,
UserName = a.UserName
}).ToList();
foreach (var model in modelList)
{
model.Images = imageService.GetImagesForArticle(model.Id.ToString());
}
return View(modelList);
}

Related

How to return list of object which associated with one ID?

I am still getting familiar with SQL and LINQ and I am trying to get every objects and its objects which is under one ID.
The below is the EDMX Diagram.
I am passing ClientID and I want to list everything that is under that ClientID and the below is my query to do so but as you can see query is only returning the first element but how to change it to return the list of every elements as below:
Passed ClientID
THeaderTitle 1
TReportName 1
TReportName 2
MY query is below which is returning the first element:
public TReportHeaderModel GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
}).First();
return query;
}
}
I've got it working!
I had to change it in my interface as
IList GetHeadersByClient (int ClientID);
So that I can return List of elements in my controller to pass to view.
public IList<TReportHeaderModel> GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var query = (from c in connection.THeader.Include("TReports")
where
c.ClientID == ClientID
select new TReportHeaderModel()
{
ID = c.ID,
THeaderTitle = c.THeaderTitle,
RowNumber = c.RowNumber,
TReports = (from t in c.TReports
select new TReportModel()
{
ID = t.ID,
TReportName = t.TReportName,
URL = t.URL,
RowNumber = t.RowNumber
}).ToList()
});
return query.ToList();
}
}

Sorting multiple LINQ results of different models as one list in MVC

I am trying to sort a list of users that are either students, colleagues or guests and sort them in my view based on their names.
Here is the code:
public ActionResult Index()
{
var db = new PraktikumDataContext();
var model = new List<AdminUserListItem>();
var studs = (from stud in db.Students select new AdminUserListItem() {Name = stud.FH_Angehörige.Name, LastLogin = stud.FH_Angehörige.FE_Nutzer.Letzter_Login, Rolle = "Student"}).OrderBy(stud => stud.Name);
model.AddRange(studs);
var mits = (from mit in db.Mitarbeiters select new AdminUserListItem() {Name = mit.FH_Angehörige.Name, LastLogin = mit.FH_Angehörige.FE_Nutzer.Letzter_Login, Rolle = "Mitarbeiter"}).OrderBy(stud => stud.Name);
model.AddRange(mits);
var gasts = (from gast in db.Gasts select new AdminUserListItem() {Name = gast.Name, LastLogin = gast.FE_Nutzer.Letzter_Login, Rolle = "Gast"}).OrderBy(stud => stud.Name);
model.AddRange(gasts);
model = model.OrderByDescending()
return View(model);
}
What I've already done with OrderBy sorts each model in it's own scope, however since I have 3 models, I am a little bit confused now how to somehow make them to be seen as one list and then sort them and show them in my website.
Consider using a LINQ union that makes a single call to the server:
public ActionResult Index()
{
var db = new PraktikumDataContext();
var model =
(from stud in db.Students
select new AdminUserListItem()
{
Name = stud.FH_Angehörige.Name,
LastLogin = stud.FH_Angehörige.FE_Nutzer.Letzter_Login,
Rolle = "Student"}
).Union(
from mit in db.Mitarbeiters
select new AdminUserListItem()
{
Name = mit.FH_Angehörige.Name,
LastLogin = mit.FH_Angehörige.FE_Nutzer.Letzter_Login,
Rolle = "Mitarbeiter"}
).Union(
from gast in db.Gasts
select new AdminUserListItem()
{
Name = gast.FH_Angehörige.Name,
LastLogin = gast.FE_Nutzer.Letzter_Login,
Rolle = "Gast"}
)
.OrderByDescending(a => a.Name)
.ToList();
return View(model);
}

StringBuilder within IEnumerable

I have a ControlMeasure table that holds information on each control measure and a ControlMeasurepeopleExposed Table that holds a record for each person exposed in the control measure this could be 1 record or many records.
I Have a controller that populates a List view
For each item in the list, Control Measure, I would like to create a string that shows all the People at risk
e.g.
PeopleString = "Employees, Public, Others";
Ive added a foreach in the controller to show what I'm trying to do however I'm aware that this wont work.
The controller is this:
public ActionResult ControlMeasureList(int raId)
{
//Populate the list
var hazards = new List<Hazard>(db.Hazards);
var controlMeasures = new List<ControlMeasure>(db.ControlMeasures).Where(x => x.RiskAssessmentId == raId);
var cmcombined = (
from g in hazards
join f in controlMeasures
on new { g.HazardId } equals new { f.HazardId }
select new CMCombined
{
Activity = f.Activity,
ControlMeasureId = f.ControlMeasureId,
ExistingMeasure = f.ExistingMeasure,
HazardName = g.Name,
LikelihoodId = f.LikelihoodId,
Rating = f.Rating,
RiskAssessmentId = f.RiskAssessmentId,
SeverityId = f.SeverityId,
}).OrderBy(x => x.Activity).ToList();
var cmPeopleExp = new List<ControlMeasurePeopleExposed>(db.ControlMeasurePeopleExposeds).Where(x => x.RiskAssessmentId == raId);
var peopleExp = from c in cmPeopleExp
join d in db.PeopleExposeds
on c.PeopleExposedId equals d.PeopleExposedId
orderby d.Name
select new RAPeopleExp
{
RAPeopleExpId = c.PeopleExposedId,
PeopleExpId = c.PeopleExposedId,
PeopleExpName = d.Name,
RiskAssessmentId = c.RiskAssessmentId,
ControlMeasureId = c.ControlMeasureId
};
var model = cmcombined.Select(t => new FullControlMeasureListViewModel
{
ControlMeasureId = t.ControlMeasureId,
HazardName = t.HazardName,
LikelihoodId = t.LikelihoodId,
Rating = t.Rating,
SeverityId = t.SeverityId,
Activity = t.Activity,
ExCM = t.ExistingMeasure,
//This section here is where I'm struggling
var PeopleString = new StringBuilder();
foreach (var p in peopleExp)
{
PeopleString.AppendLine(p.PeopleName);
{
PeopleExposed = PeopleString,
});
return PartialView("_ControlMeasureList", model);
}
I know I cant directly put this code in the controller but it does represent what I want to do.
You can't foreach within an object initializer (which is what you're trying to do when instantiating FullControlMeasureListViewModel). You can, however, use a combination of string.Join and peopleExp.Select:
var model = cmcombined.Select(t => new FullControlMeasureListViewModel
{
//other props
PeopleExposed = string.Join(",", peopleExp
.Where(p => p.ControlMeasureId == t.ControlMeasureId)
.Select(p => p.PeopleExpName));
//other props
});

Cannot be constructed in a LINQ to Entities query. Error

public ActionResult CreateApp(Guid id)
{
SMICParkingLotApplicationEntities1 dbb = new SMICParkingLotApplicationEntities1();
ApplicationDATA applicationData = (from a in dbb.ApplicationDATAs
where a.ApplicationID == id
select new ApplicationDATA
{
ApplicationID = a.ApplicationID,
BrandModel = a.BrandModel,
CrNo = a.CrNo,
OrNo = a.OrNo,
DatePosted = a.DatePosted,
PoR = a.PoR,
PlateNo = a.PlateNo,
VehicleType = a.VehicleType
}).FirstOrDefault();
ApplicationSlotViewModel applicationSlotViewModel = new ApplicationSlotViewModel
{
ApplicationDatas = applicationData,
Application = new Application()
};
return View(applicationSlotViewModel);
Dunno what to do it always shows this error Cannot be constructed in a LINQ to Entities query. Error Help Plss..
If the type of ApplicationDatas in your ViewModel is ApplicationDATA, you can set it directly with the result of your query:
var applicationData =dbb.ApplicationDATAs.FirstOrDefault(a=>a.ApplicationID == id);
ApplicationSlotViewModel applicationSlotViewModel = new ApplicationSlotViewModel
{
ApplicationDatas = applicationData,
Application = new Application()
};
You can't project the result of your query using an existing entity type. Check the post that I quote in my comment
Remove className after new keyword. Try below code.
var applicationData = (from a in dbb.ApplicationDATAs
where a.ApplicationID == id
select new
{
ApplicationID = a.ApplicationID,
BrandModel = a.BrandModel,
CrNo = a.CrNo,
OrNo = a.OrNo,
DatePosted = a.DatePosted,
PoR = a.PoR,
PlateNo = a.PlateNo,
VehicleType = a.VehicleType
}).FirstOrDefault();

How can I save a viewmodel for postback viewing?

I am working on MVC project where I have successfully created a search page with several dropdowns and textboxes. After the user queries the data, they are then transferred to a List page with a list of results corresponding to our search. I was wondering if it is possible to create a button located on the List view that returns them back to the search page, the search page's textboxes/dropdowns still populated with their previous search. Currently, when they return, their previous search was cleared, and they can't see what was queried.
Simplified: Is there a way to capture the data of a viewmodel on query submit, and then be able to access it with simple return button.
Get Method (populates dropdown etc)
[HttpGet]
public ActionResult Index()
{
//testTypes
var testTypesL = new List<string>();
var testTypesQr = from z in db.Results
orderby z.TestType
select z.TestType;
testTypesL.AddRange(testTypesQr.Distinct());
//technicians
var techniciansL = new List<string>();
var techniciansQr = from z in db.Results
orderby z.Technician
select z.Technician;
techniciansL.AddRange(techniciansQr.Distinct());
//engineers
var engineersL = new List<string>();
var engineerQr = from z in db.Results
orderby z.Engineer
select z.Engineer;
engineersL.AddRange(engineerQr.Distinct());
//testStalls
var testStallL = new List<string>();
var testStallQr = from z in db.Results
orderby z.TestStall
select z.TestStall;
testStallL.AddRange(testStallQr.Distinct());
//unit models
var unitModelL = new List<string>();
var unitModelQr = from z in db.Results
orderby z.UnitID
select z.UnitID;
unitModelL.AddRange(unitModelQr.Distinct());
TestDataViewModel obj = new TestDataViewModel();
obj.EngineerList = new SelectList(engineersL);
obj.TechnicianList = new SelectList(techniciansL);
obj.TestStallList = new SelectList(testStallL);
obj.UnitModelList = new SelectList(unitModelL);
obj.TestTypeList = new SelectList(testTypesL);
return View("Index", obj);
}
Post Method: (sends user query to the List view)
[HttpPost]
public ActionResult Index(TestDataViewModel obj)
{
var data = from d in db.Results
select d;
//search data parameters
if (!String.IsNullOrEmpty(obj.StartDate.ToString()) && !String.IsNullOrEmpty (obj.EndDate.ToString()))
{
data = data.Where(z => obj.StartDate <= z.EndDate && obj.EndDate >= z.EndDate);
}
if (!String.IsNullOrEmpty(obj.TestNumber.ToString()))
{
data = data.Where(z => z.TestNumber == obj.TestNumber);
}
if (!String.IsNullOrEmpty(obj.unitModel))
{
data = data.Where(z => z.UnitID == obj.unitModel);
}
if (!String.IsNullOrEmpty(obj.Project))
{
data = data.Where(z => z.ProjectNum.Contains(obj.Project));
}
if (!String.IsNullOrEmpty(obj.testType))
{
data = data.Where(z => z.TestType == obj.testType);
}
if (!String.IsNullOrEmpty(obj.engineer))
{
data = data.Where(z => z.Engineer == obj.engineer);
}
if (!String.IsNullOrEmpty(obj.technician))
{
data = data.Where(z => z.Technician == obj.technician);
}
if (!String.IsNullOrEmpty(obj.testStall))
{
data = data.Where(z => z.TestStall == obj.testStall);
}
return View("List", data);
}

Categories

Resources