Linq Results into IEnumerable in ViewModel in ASP.NET MVC Controller - c#

I am trying to put my linq query results into view model but I keep getting an error. Linq query returns multiple rating results. I would like to put these multiple rating results in an IEnumerable.
Error: Cannot implicitly convert type Models.CustomerRating' to 'System.Collections.Generic.IEnumerable<Models.CustomerRating>'. An explicit conversion exists (are you missing a cast?)
Linq query
var data = from profile in _context.Customers
join rating in _context.CustomerRating
on profile.strUserID equals rating.strUserID into rt
from subrating in rt.DefaultIfEmpty()
where profile.strUserID == UserId
select new { p = profile, r = subrating };
My view model:
public class ServiceProvider
{
public CustomerProfile Customer { get; set; }
public IEnumerable<CustomerProfile> CustomerProfiles { get; set; }
public CustomerServices CustomerServices { get; set; }
public FilterServicesViewModel FilterServices { get; set; }
public CustomerRating Rating { get; set; }
public IEnumerable<CustomerRating> CustomerRating { get; set; }
}
I would like to the results of profile to be added to Customer and subrating to CustomerRating IEnumerable.
I have tried the following but I get an error:
foreach (var v in data)
{
serviceProviderViewModel.Customer = v.p;
serviceProviderViewModel.CustomerRating = v.r;
}

Create a new list and loop through your linq query results and add it to that list
List<CustomerRating> RatingList = new List<CustomerRating>();
foreach (var v in data)
{
serviceProviderViewModel.Customer = v.p;
RatingList.Add(v.r);
}
serviceProviderViewModel.CustomerRating = RatingList;

Related

Comparing two table IDs. ASP.NET MVC

I am currently loading two Orders and Colors tables, I wanted the Colors table to list the items that have the ID equal to Orders. For this, what occurred to me was to assign the IdOrders values ​​to a variable and compare it with my IdOrders (in my table Colors), but it is not possible to assign the database's balance to my variable
My tables:
public partial class Orders
{
public int ID_Orders { get; set; }
public Nullable<System.DateTime> Data_Registo { get; set; }
public string Num_Encomenda { get; set; }
public string Ref_Cliente { get; set; }
}
public partial class Colors
{
public int ID_Orders { get; set; }
public int ID_Programa_Malha { get; set; }
public int ID_Linha_Cor { get; set; }
public string Cor { get; set; }
}
I am working with a database already in operation and possible these tables are already used in a sql join but not how to process that information.
As I said the first thing I remembered was to do this:
My Controller:
var id = from d in db.Orders
select d.ID_Orders;
var color = db.Colors.Where(x => x.ID_Orders = id).ToList();
var tables = new EncomendaViewModel
{
Orders= db.Orders.ToList(),
Colors= color.ToList(),
};
return View(tables);
Error in id: CS0029 C# Cannot implicitly convert type to 'int'
Is it possible to process the data in this way?
Thanks for anyone who can help!
-------------------(Update)------------------------------------------------
Using == cs0019 operator '==' cannot be applied to operands of type
My view in Broswer
dbEntities sd = new dbEntities();
List<Orders> orders= sd.Orders.ToList();
List<Colors> colers= sd.Colors.ToList();
var multipletable = from c in orders
join st in colers on c.ID_Programa equals st.ID_Programa into table1
from st in table1.DefaultIfEmpty()
select new MultipleClass { orders= c, colers= st };
There could be one or more values returned from the below query.
var id = from d in db.Orders
select d.ID_Orders;
That is the reason why it was throwing an error.
So lets try it this way
var color = db.Colors.Where(x => id.Contains(x.ID_Orders)).ToList();
public class OrderWithColorsViewModel
{
public Order order { get; set; }
public List<Colors> colers{ get; set; }
}
Public class TestOrderController : Controller
{
public DailyMVCDemoContext db = new DailyMVCDemoContext();
public ActionResult Index()
{
var orders= db.Orders.ToList();
var colers = db.Colors.ToList();
var result = (from c in orders
join st in colers on c.ID_Orders equals st.id into table1
select new OrderWithColorsViewModel { order =c, colers =
table1.ToList() }).ToList();
return View(result);
}
}
credits: YihuiSun

LINQ- filer as required model and add a list to the select statement

I need to access to the following list.
Mainlist - contains equipmentlist and it will display with the following model.
public class BTypeModel
{
public string Image { get; set; }
public int? id { get; set; }
public string bName { get; set; }
public string alterName { get; set; }
public string number { get; set; }
public List<MainEquipment> equipment { get; set; }
public string displayName { get; set; }
}
public class MainEquipment
{
public int id { get; set; }
public string name { get; set; }
}
My issue is that I can not access the equipemnt list
see as follow
var available = MainList
.Where(o => o.bType?.id == placeid)
.Select(s => new BTypeModel {
displayName = s.Type.name,
id = s.id,
number = s.number,
Image = s.files.FirstOrDefault()?.Image,
alterName = s.alternateName,
equipment=s.mainequipmentlist.Select(a=>a.id), *
//The select is what gives the error. no matter if I select the int or the string the error is the same just change
'System.Collections.Generic.IEnumerable' Cannot implicitly
convert type 'System.Collections.Generic.IEnumerable' to to
'System.Collections.Generic.List'. An
explicit conversion exists (are you missing a cast?)
equipment=s.mainequipmentlist.Select(a=>a.id)
I can't get it to display this list -** error is can convert int to a generic list- **
equipment property in BTypeModel class is of type List<MainEquipment>, your equipment=s.mainequipmentlist.Select(a=>a.id) is projecting only ids using Select() method.
equipment=s.mainequipmentlist.Select(a=>a.id) will return IEnumerable and trying to assign it to List<MainEquipment>. This is the reason behind an error.
To fix this issue either assign s.mainequipmentlist to equipment property instead. Or create new property in BTypeModel for equipmentIds of type IEnumerable<int> and assing it projected ids like
var available = MainList
.Where(o => o.bType?.id == placeid)
.Select(s => new BTypeModel {
...
equipment = s.mainequipmentlist, //Either
ids = s.mainequipmentlist.Select(a=>a.id) //or solution
...
}
Enumerable.Select Method
I used this as reference
convert ienumerable linq list to typed list
instead of this
equipment=s.mainequipmentlist.Select(a=>a.id),
do this - convert to a model
equipment = s.mainequipmentlist.Select(p => new BTypeModel {name= p.name ,id=p.id }).ToList()

How can I extract data from a list of parent objects with children?

If I have a list inside a class inside of a list where the classes are defined like so:
class Class1
{
public int Id { get; set; }
public List<Class2> Class2s { get; set; }
}
class Class2
{
public string Name { get; set; }
public string Value { get; set; }
}
I can create a list of a class of type Result where Result is:
class Result
{
public int Class1Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
Note that the Result class contains values from Class1 and Class2.
Like so:
var results = new List<Result>();
foreach (var class1 in class1s) //class1s is a List of Class1
{
foreach (var class2 in class1.Class2s)
{
results.Add(new Result()
{
Class1Id = class1.Id,
Name = class2.Name,
Value = class2.Value,
};
}
}
How can I do this via a linq query?
I have tried the following:
IList<Result> list = class1s.Select(c => c.Class2s.Select(c2 => new Result()
{
Class1Id = c.Id,
Type = c2.Type,
Name = c2.Name,
}).ToList()).ToList();
But this fails with the error:
Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.List<Results>' to 'System.Collections.Generic.IList<Results>'. An explicit conversion exists (are you missing a cast?)
NOTE:
The duplicates do not answer the question as they do not address the issue when the resultant list is a list of the inner classes AND using a property of the inner class.
Retrieving data from a list of parents and children can be done easily in query format by using two from statements
var results = from parent in class1s
from child in parent.Class2s
select new Result {
Class1Id = parent.Id,
Name = child.Name,
Value = child.Value,
};
var list=results.ToList();
In the fluent format, you can use SelectMany
var list = class1s.SelectMany(parent => parent.Class2s,
(parent,child)=>
new Result {
Class1Id = parent.Id,
Name = child.Name,
Value = child.Value
}
).ToList();
I prefer the first form for obvious reasons
Notice that I use the SelectMany overload that accepts a result selector. Without it I'd have to use a Select inside the first selector function, resulting in even more cumbersome code
You can do this in non-query format using the following:
results = class1s.SelectMany(c => c.Class2s.Select(c2 => new Result()
{
Class1Id = c.Id,
Name = c2.Name,
Value = c2.Value,
})).ToList();
Note that it's very similar to your original attempt but using SelectMany on the class1s rather than Select.

join data in linq if only data for object is available from view model - ASP.net -mvc5

I have viewModel that extract of multiple model classes. I am binding data and then passing to razor partial view to show data however I am getting error if one of the model object is null. In my business process it is expected however my question is can I use if condition is Linq--Joins i.e. that join result only if data exist in database or is there any better way to do it.
public StudentDetailedProfileViewModel GetStudentDetailedProfileByStudentID(int _studentID)
{
try
{
using (var _uow = new StudentProfile_UnitOfWork())
{
StudentDetailedProfileViewModel StudentProfileObject = new StudentDetailedProfileViewModel();
var _profile = (from _student in _uow.Student_Repository.GetAll()
join _contactDetail in _uow.ContactDetail_Repository.GetAll() on _student.StudentID equals _contactDetail.StudentID
join _addressDetail in _uow.Address_Repository.GetAll() on _student.StudentID equals _addressDetail.StudentID
join _studentCourse in _uow.Course_Repository.GetAll() on _student.StudentID equals _studentCourse.StudentID
join _school in _uow.School_Repository.GetAll() on _studentCourse.SchoolID equals _school.SchoolID
join _campus in _uow.Campus_Repository.GetAll() on _studentCourse.CampusID equals _campus.CampusID
where _student.StudentID == _studentID
select new StudentDetailedProfileViewModel { _studentModel = _student, _contactDetailModel = _contactDetail, _addressModel = _addressDetail , _courseModel = _studentCourse,_schoolModel = _school, _campusModel = _campus}).FirstOrDefault();
_profile._emergencyContactModel = (from _emergencyContact in _uow.EmergencyContact_Repository.GetAll()
where _emergencyContact.StudentID == _studentID
select _emergencyContact).ToList();
return _profile;
}
}//
catch { return null; }
}
......
public class StudentDetailedProfileViewModel
{
public StudentDetailedProfileViewModel() { }
public Student _studentModel { get; set; }
public Course _courseModel { get; set; }
public School _schoolModel { get; set; }
public Campus _campusModel { get; set; }
public ContactDetail _contactDetailModel { get; set; }
public Address _addressModel { get; set; }
public List<EmergencyContact> _emergencyContactModel { get; set; }
}
Instead of JOINing, if your root entity (Student) has navigation properties to the child collections (and the associations are configured in your entity model) you could Include() them. Let LINQ generate the select statement rather than trying to figure it out beforehand.

How to assign a anonymous type to a model?

How to assign a anonymous type to a model?
Using ViewBag I could easily assign like that:
ViewBag.certType = comboType.ToList();
I am removing all ViewBags from my system and now I am trying like that:
model.storeLocations = comboType.ToList();
I am getting the following error:
Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>'
to 'int' S:\Projects\tgpwebged\tgpwebged\Controllers\AdminController.cs
376 40 tgpwebged
Model:
public class TipoDocumentoModel
{
public sistema_DocType Type { get; set; }
public IEnumerable<string> Indices { get; set; }
public IEnumerable<string> NonAssoIndices { get; set; }
public int storeLocations { get; set; }
}
controller:
public ActionResult AdminSettingAddTipo()
{
SettingsModels.TipoDocumentoModel model = new SettingsModels.TipoDocumentoModel();
//Pega os indices e locais de armazenamentos cadastrados no sistema
using (tgpwebgedEntities context = new tgpwebgedEntities())
{
var obj = from u in context.sistema_Indexes select u.idName;
model.Indices = obj.ToList();
var comboType = from c in context.sistema_Armazenamento
select new
{
id = c.id,
local = c.caminhoRepositorio
};
model.storeLocations = comboType.ToList();
}
return PartialView(model);
}
First problem is you are trying to assign a List<> of items to an int property.
Easy way extract out a named class from the anonymous projection.
//model
public List<MyClass> storeLocations { get; set; }
//snip
var comboType = from c in context.sistema_Armazenamento
select new MyClass
{
id = c.id,
local = c.caminhoRepositorio
};
storeLocations = comboType.ToList();
Other Options
If you still want the dynamic behavior you could change your property to be dynamic
Project into a Tuple<int, string>() (guessing on second type)
If the end result is a drop down list you could project into a SelectList()

Categories

Resources