Build ViewModel using two models
Model 1: Person (Id,Name,Address,Phone,CategoryId)
Model 2: Category(CategoryId,CategoryText)
ViewModel: PersonViewModel (Name,Phone, CategoryText)
Question: how would I generate my ViewModel in my controller and forward it to the view:
var model = (from x in db.Person
select new PersonViewModel {
Name = x.Name,
Phone = x.Phone,
CategoryText = ??? }).ToList();
How do I generate CategoryText?
Thanks
You need to join on categories.
you may be able to include as the following, if not you just need a join. Try the following (I forget if you can include() in this syntax - somethingin my mind tells me you can't and if that's the case I'll delete this shortly as I see someone just posted the join syntax)
var model = (from x in db.Person.Include(o=>o.Category) //assumes EF 4.1 if not try .Include("Category")
select new PersonViewModel {
Name = x.Name,
Phone = x.Phone,
CategoryText = x.Category.CategoryText }).ToList();
var model = (from x in db.Person
join y from db.Category on x.CategoryId equals y.CategoryID
select new PersonViewModel {
Name = x.Name,
Phone = x.Phone,
CategoryText = y.CategoryText }).ToList();
Related
I've got a class that contains a list item. I would like for a linq query to populate the class, including this list. Here is my query:
var query = from c in context.Cars
select new CarListItem()
{
ID = c.ID,
Make = c.Make,
AvailableColors = context.CarColors.Where(u => u.CarID == c.ID).ToList()
};
Basically, I want to get a list of all of the cars, including a list of the available colors for each respective car.
The problem is that the inclusion of .ToList() within the query results in an error: An error occurred:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[CarSystem.Models.CarColors] ToList[CarColors](System.Collections.Generic.IEnumerable`1[CarSystem.Models.CarColors])' method, and this method cannot be translated into a store expression.
At this point, I don't know whether I am just using wrong syntax within the Linq query (should I use something other than .ToList()?) or if maybe the architecture of the models is wrong.
You can't. EF tries to translate ToList() to SQL and doesn't know how.
You could project to another type, then call ToList():
var query = (from c in context.Cars
select new
{
ID = c.ID,
Make = c.Make,
AvailableColors = context.CarColors.Where(u => u.CarID == c.ID)
}).ToList()
.Select(c => new CarListItem()
{
ID = c.ID,
Make = c.Make,
AvailableColors = c.AvailableColors.ToList()
});
or change the type of CarListItem.AvailableColors to IEnumerable<CarColor>:
var query = from c in context.Cars
select new CarListItem()
{
ID = c.ID,
Make = c.Make,
AvailableColors = context.CarColors.Where(u => u.CarID == c.ID)
};
I Using Two Table User And Location In User Table I having LocationId And When I'm going to edit The User Form Then I need User With There Exact Location In Drop Down.but i didn't get that this is my code Of Controller:-
LogisticsEntities db = new LogisticsEntities();
RegisterModel Reg = new RegisterModel();
var tempUser = (from c in db.Users select new RegisterModel { _UserId = c.UserID, UserName = c.Name, Code = c.Code, Email = c.Email, Phone = c.Phone, JobRole = c.JobRole, StartDate = c.StartDate, EndDate = c.EndDate, LocationId = c.Location }).SingleOrDefault(x => x._UserId == id);
var varLocation = from Ls in db.Locations select Ls;
ViewData["LocationId"] = new SelectList(varLocation.ToList(), "LocationID", "Location1", "2");
if (tempUser != null)
return View(tempUser);
else
return View();
And In My View I Have code: -
#Html.DropDownList("LocationID", (SelectList)ViewData["LocationId"])
Thanx In Advance..
You are using LocationID as both first parameter of the dropdown and inside ViewData. In order to generate a dropdown you need 2 things: the first argument will be used to generate the name attribute of the dropdown and used to bind the value back and the second argument must represent a collection of SelectListItem that will be used to create the options of the dropdown. So try using a different key for the collection:
ViewData["locations"] = new SelectList(varLocation.ToList(), "LocationID", "Location1", "2");
and then:
#Html.DropDownList("LocationID", (SelectList)ViewData["locations"])
Hi i am new to MVC3 Razor .
I was trying to display the values from the database table.
in controller i wrote the code as
var test1 = from ed in db.EmpDetails
join dp in db.Departments on ed.EmpDept equals dp.DeptId
select new
{
EmpId = ed.EmpId,
EmpName = ed.EmpName,
EmpDesignation = ed.EmpDesignation,
EmpSalary = ed.EmpSalary,
EmpUserName =ed.EmpUserName,
EmpDept =ed.EmpDept,
deptName = dp.deptName
};
ViewBag.test = test1;
and in the view
#foreach (var tm in ViewBag.test)
{
string abc =#tm.EmpName;
// and the logic
}
Here i am getting all the value in the "tm" variable. But when i try to get the particular value of EmpName in a string it is showing the error as "'object' does not contain a definition for 'EmpName'".
Please help me to solve this error.
Thanks
san
Unfortunately anonymous objects doesn't work with Views. Either you need to return a non-anonymous to view Or return a dynamic object to view.
Refer : http://rhizohm.net/irhetoric/post/2011/05/25/Taking-The-M-out-of-MVC-JSON-The-dynamic-Keyword-LINQ-.aspx
You cannot use anonymous objects in views. Try like this:
var test1 =
from ed in db.EmpDetails
join dp in db.Departments on ed.EmpDept equals dp.DeptId
select ed;
ViewBag.test = test1;
and then:
#foreach (var tm in (IEnumerable<Employee>)ViewBag.test)
{
string abc = tm.EmpName;
// and the logic
}
But personally I would recommend you using strongly typed views instead of ViewBag:
var test1 =
from ed in db.EmpDetails
join dp in db.Departments on ed.EmpDept equals dp.DeptId
select ed;
return View(test1);
and inside the view:
#model IEnumerable<Employee>
#foreach (var tm in Model)
{
string abc = tm.EmpName;
// and the logic
}
I am able to get the values in the view if i convert linq result to toList() in controller.
Like
var test = (from p in db.EmpDetails orderby p.EmpName ascending select p).ToList();
ViewBag.test = test;
And in the view
#foreach (var tm in ViewBag.test)
{
int emId = #tm.id;
}
Thanks....
I have a MVC 2 project, using Entity Framework, in Visual Studio 2010 and I have a class 'ProductModel' which is doing a LINQ query to return an product from the database.
I want to return Products objects instead of the default "entities" query objects so I founded that I had to do like this:
var product = from x in productosBD.Products
where x.Id == id
select new ProductoModels { Id = x.Id, NombreCorto = x.NombreCorto, NombreLargo = x.NombreLargo, Pvp = x.Pvp .... };
The problem is that I have to do ALL the assignations with all the attributes of the database table (could be 30 easily) So my question is : Is there any way to do a mapping of the database entities with my objects class automatically? Something like:
var product = from xin productosBD.Products
where x.Id == id
select x;
but retorning a Products object?
Thanks in advance
Automapper : http://automapper.codeplex.com/
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/01/22/automapper-the-object-object-mapper.aspx
public static void Configure() {
Mapper.CreateMap<Order, OrderViewModel>();
Mapper.CreateMap<OrderLineItem, OrderLineItemViewModel>();
}
var viewModel = Mapper.Map<Order, OrderViewModel>(order);
So I'm new to linq so be warned what I'm doing may be completely stupid!
I've got a table of caseStudies and a table of Services with a many to many relasionship
the case studies already exist and I'm trying to insert a service whilst linking some case studies that already exist to it. I was presuming something like this would work?
Service service = new Service()
{
CreateDate = DateTime.Now,
CreatedBy = (from u in db.Users
where u.Id == userId
select u).Take(1).First(),
Description = description,
Title = title,
CaseStudies = (from c in db.CaseStudies
where c.Name == caseStudy
select c),
Icon = iconFile,
FeatureImageGroupId = imgGroupId,
UpdateDate = DateTime.Now,
UpdatedBy = (from u in db.Users
where u.Id == userId
select u).Take(1).First()
};
But This isn't correct as it complains about
Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Objects.DataClasses.EntityCollection'
Can somebody please show me the correct way.
Thanks in advance
Yo have to add the query result to the case studies collection instead of trying to replace it.
var service = new Service { ... };
foreach (var caseStudy in db.CaseStudies.Where(s => s.Name == caseStudyName)
{
service.CaseStudies.Add(caseStudy);
}
You can wrap this in an extension method and get a nice syntax.
public static class ExtensionMethods
{
public static void AddRange<T>(this EntityCollection<T> entityCollection,
IEnumerable<T> entities)
{
// Add sanity checks here.
foreach (T entity in entities)
{
entityCollection.Add(entity);
}
}
}
And now you get the following.
var service = new Service { ... };
service.CaseStudies.AddRange(db.CaseStudies.Where(s => s.Name == caseStudyName));