Would anyone of you could help me solve this? I'm getting this error when casting 'carsList' variable to '_vehicleList'
Unable to cast object of type 'System.Data.Linq.DataQuery to type 'System.Collections.Generic.List`1[VehicleDAOModel]'.
Does the Linq.DataQuery has to match the Properties in VehicleDAOModel?
My code:
public class VehicleDAOModel
{
[Display(Name = "Id")]
public int _Id { get; set; }
[Required]
[Display(Name = "Year")]
public string _year { get; set; }
[Required]
[Display(Name = "Make")]
public string _make { get; set; }
[Required]
[Display(Name = "Model")]
public string _model { get; set; }
[Required]
[Display(Name = "Trim")]
public string _trim { get; set; }
}
// LINQ TO SQL CODE
var dataContext = new VehicleModelL2SQLDataContext();
var carsList = from v in dataContext.Vehicles
select v;
_vehicleList = (List<VehicleDAOModel>)carsList;
public List<VehicleDAOModel> _vehicleList = new List<VehicleDAOModel>();
Tried the following but did NOT work:
carsList.ToList(); (X)
carsList.AsEnumerable().LoList(); (X)
Thank you in advance.
Just do a .ToList()on that carsList.
_vehicleList = carsList.ToList();
That carsList is a query that will be executed, once it's read from. The .ToList() reads the complete query result and returns it as a List<T>.
But that does expect the query to return VehicleDAOModels. If not, then you will need to use .Select() and convert it yourself.
Assuming that your vehicle entity class is not named "VehicleDAOModel" you need to project carsList to a list of VehicleDAOModel objects.
_vehicleList = carsList.Select( c =>
new VehicleDAOModel {
Id = c.Id,
Year = c.Year,
...
});
I would strongly recommend to use Automapper for this:
Mapper.Map<Vehicle, VehicleDAOModel>();
_vehicleList = carsList.Project.To<VehicleDAOModel>();
(Assuming that there is a 1:1 mapping of property names between both classes.)
Related
here is my setup.
Base Model
public class Base
{
public int BaseID { get; set; }
[StringLength(8)]
[Index(IsUnique = true)]
public string BaseNumber { get; set; }
public ICollection<BillOfMaterial> billOfMaterials { get; set; }
}
BillOfMaterial Model
public class BillOfMaterial
{
public int BillOfMaterialID { get; set; }
[StringLength(10)]
[Index(IsUnique = true)]
public string BomNumber { get; set; }
public ICollection<Base> Bases { get; set; }
}
What I am trying to do is select all bill of material BomNumbers where the base is equal to a input base number.
What I have tried
BaseNumber = "A1C1D001";
var BOMQuery = (from Base in db.Bases.Include("BillOfMaterials")
where Base.BaseNumber == BaseNumber
select Base.billOfMaterials.ToList());
When trying to create this query I can't see the BomNumber property when I do => select Base.BillOfMaterials.(Can't Find Property)
I tried using the .Include() extension to try and bring in the related table in hopes it would give me the property. Not sure how to word this question exactly to do a good google search for the answer. What am I doing wrong here? Any help would be appreciated.
Thank you,
When you only need a list of BOMs use the following:
var BOMQuery = db.Bases
.Where(x => x.BaseNumber == BaseNumber)
.SelectMany(a => a.billOfMaterials.Select(b => b.BomNumber)).ToList();
You can then add it to an ObservableCollection like this:
BomList = new ObservableCollection<string>(BOMQuery);
I have some code that is functioning oddly and was wondering if anyone else hase come across this issue.
I have a view model that collects data from a database via a stored procedure and a vb object (no I do not know vb this is legacy)
When I execute the program the data is collected as expected via the controller. When I debug it I can see all of my parameters populating with information. However when it comes to the view it says that the parameters are null. I have included my code
Models:
public class PersonIncomeViewModel
{
public string IncomeTypeDesc { get; set; }
public string IncomeDesc { get; set; }
public string Income { get; set; }
}
public class PersonIncomeListViewModel
{
public int? PersonId { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonIncomeListViewModel()
{
Incomes = new List<PersonIncomeListItem>();
}
}
public class PersonLookupViewModel : Queue.QueueViewModel
{
public int Action { get; set; }
public bool ShowAdvancedFilters { get; set; }
//Person Search Variables
[Display(Name = #"Search")]
public string SpecialSearch { get; set; }
[Display(Name = #"Person Id")]
public int? PersonId { get; set; }
[Display(Name = #"Full Name")]
public string FullName { get; set; }
[Display(Name = #"SSN")]
public string SSN { get; set; }
public string AddressStatus { get; set; }
public string EmploymentStatus { get; set; }
public PersonIncomeViewModel Income { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonLookupViewModel()
{
Income = new PersonIncomeViewModel();
Incomes = new List<PersonIncomeListItem>();
}
}
Controller:
public ActionResult _Income(int id)
{
var vm = new PersonLookupViewModel();
var personManager = new dtPerson_v10_r1.Manager( ref mobjSecurity);
//var person = personManager.GetPersonObject((int)id, vIncludeIncomes: true);
var person = personManager.GetPersonObject(id, vIncludeIncomes: true);
var look = JsonConvert.SerializeObject(person.Incomes);
foreach (dtPerson_v10_r1.Income income in person.Incomes)
{
if (income.IncomeType_ID == 0)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Unknown",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 1)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Alimony",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 2)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Child Support",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
}
return PartialView(vm);
}
View:
#using dtDataTools_v10_r1
#using ds_iDMS.Models.Person
#model ds_iDMS.Models.Person.PersonLookupViewModel
#{
var format = new dtDataTools_v10_r1.CustomFormat();
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
}
using (Html.DSResponsiveRow(numberOfInputs: ExtensionMethods.NumberOfInputs.TwoInputs))
{
using (Html.DSCard(ExtensionMethods.Icon.CustomText, iconInitials: newInitials, color: ExtensionMethods.Colors.PrimaryBlue))
{
<div>#Model.Income.IncomeTypeDesc</div>
<div>#Model.Income.IncomeDesc</div>
<div>#Model.Income.Income</div>
}
}
There are some extensions that we have built but they are irrelevant to the issue
The line that errors out is this one:
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
Which drives all of the extension methods on the view and as I run the debugger over it all of the parameters read null, however like I said when I run the debugger and check them in the controller they are populated properly.
Sorry about the long post but I wanted to ensure all the detail was there
This is how to pass the Object model to your Partial View
return PartialView("YourViewName", vm);
or using the Views path
return PartialView("~/YourView.cshtml", vm);
EDIT
Try starting your Action Method like this
var vm= new Person();
vm.PersonLookupViewModel = new PersonLookupViewModel();
Problem solved I had issues with some of my vb objects and had the vb person take a look at them and she fixed them.
Thank you for all the help
EDIT
What had to happen is the vb object had to be re-written and my logic was just fine as it was in the beginning. I marked the one response to my question as the answer because had it been in true MVC without vb objects attached to it, that would have worked perfectly
I have seen this done in code once or twice but can't find an example now. Until recently I was working in webforms and have switched to MVC. I have looked around and not found a whole lot on this. The code below is from my controller to pull in the values and display in my view model. I need to take the m.body.MembersId from MSMQ. I know what the problem is I just dont know how to use Linq like this.
The Situation , I need to do all this in one line. Cast the memberIds information that was originally a list named MembersId back to a list to display it but also do a string.join so that the entire list is displayed as one string. While I am aware of how to do both of those by themselves but to do in one line is proving beyond me. I will openly admit I am fairly new to linq and am learning as I go.
This is the class
public class MsgChildClass{
public string SourceSystem { get; set; }
public List<string> MemberIds { get; set; }
public string ParentId { get; set; }
public string Error { get; set; }
}
this is the function
public ActionResult GetAllMessages() {
string queueName = (ViewBag.QueueName != null) ? ViewBag.QueueName : Request.QueryString["queueName"];
Session["CurrentQueueName"] = queueName;
TempData["queueName"] = queueName;
ViewBag.QueueName = queueName;
var queue = _Queues[queueName];
queue.MessageReadPropertyFilter.ArrivedTime = true;
queue.MessageReadPropertyFilter.Body = true;
queue.Formatter = new JsonMessageFormatter();
var messages = queue.GetMessages();
var model = messages.Select(m =>
new ViewModel() {
Id = m.Id,
Date = m.ArrivedTime,
SourceSystem = ((MsgChildClass)m.Body).SourceSystem,
DeletedMemberIds = ((MsgChildClass)m.Body).DeletedMemberIds,//OrderByDescend(x => x); string.Join(",",((MsgChildClass)m.Body).DeletedMemberIds),
ParentMemberId = ((MsgChildClass)m.Body).ParentId,
Error = ((MsgChildClass)m.Body).Error,
QueName = queueName
}).ToList();
return Json(model.ToList(), JsonRequestBehavior.AllowGet);
}
View Model
public class ViewModel
{
[Required]
public string Id { get; set; }
//[Required]
[Display(Name = "Arrival Time")]
public DateTime Date { get; set; }
[Required]
[Display(Name = "Source System")]
public string SourceSystem { get; set; }
[Required]
[Display(Name = "Member Ids")]
public List <string> MemberIds { get; set; }
[Required]
[Display(Name = "Parent Member Id")]
public string ParentMemberId { get; set; }
[Display(Name = "Error")]
public string Error { get; set; }
[Display(Name = "QueName")]
public string QueName { get; set; }
}
This is what I have. All of it works correctly except the memberids. Debugging shows me that the memberids have the value but I am not drilling down far enough. So hopefully some one can help me out quite a bit as been quite few hours at this point. Google is great but he didnt help me out with this one.
It's cleaner and more efficient if you only cast once into a variable. And another advantage is that you can add a break point and look at msgChild.
var model = messages.Select(m =>
{
var msgChild = (MsgChildClass)m.Body;
return new ViewModel
{
Id = m.Id,
Date = m.ArrivedTime,
SourceSystem = msgChild.SourceSystem,
MemberIds = msgChild.MemberIds,
ParentMemberId = msgChild.ParentId,
Error = msgChild.Error,
QueName = queueName
};
}).ToList();
The code was correct which was the maddening part. debugger was telling me the values were there. But the part I didnt look at was how the datatable.js was loading the data for display. After seeing that was done incorrect, I corrected it and now the list is now displayed as string , string, string which is what I was needing so thanks every one
My data is having following structure
public enum ParamType
{
Integer=1,
String=2,
Boolean=3,
Double=4
}
public class Gateway
{
public int _id { get; set; }
public string SerialNumber { get; set; }
public List<Device> Devices { get; set; }
}
public class Device
{
public string DeviceName { get; set; }
public List<Parameter> Parameters { get; set; }
}
public class Parameter
{
public string ParamName { get; set; }
public ParamType ParamType { get; set; }
public string Value { get; set; }
}
I filled 10 document objects of Gateway in a MongoDB database.
Now I want to query all those gateways which contains a device having Parameter with ParamName as "Target Temperature" and whose Value > 15.
I created following queries
var parameterQuery = Query.And(Query<Parameter>.EQ(p => p.ParamName, "Target Temperature"), Query<Parameter>.GT(p => int.Parse(p.Value), 15));
var deviceQuery = Query<Device>.ElemMatch(d => d.Parameters, builder => parameterQuery);
var finalQuery = Query<Gateway>.ElemMatch(g => g.Devices, builder => deviceQuery);
But when I run this, it is giving an exception
Unable to determine the serialization information for the expression: (Parameter p) => Int32.Parse(p.Value)
Please suggest where I am wrong.
As the error suggests, you can't use Int32.Parse inside your query. This lambda expression is used to get out the name of the property and it doesn't understand what Int32.Parse is.
If you are querying a string, you need to use a string value for comparison:
var parameterQuery = Query.And(Query<Parameter>.EQ(p => p.ParamName, "Target Temperature"), Query<Parameter>.GT(p => p.Value, "15"));
However, that's probably not what you want to do since you're using GT. To be treated as a number for this comparison you need the value to actually be an int in mongo, so you would need to change the type of your property:
public class Parameter
{
public string ParamName { get; set; }
public ParamType ParamType { get; set; }
public int Value { get; set; }
}
var parameterQuery = Query.And(Query<Parameter>.EQ(p => p.ParamName, "Target Temperature"), Query<Parameter>.GT(p => p.Value, 15));
Summary
I ran into this when I was modifying a list. It appears that Linq First/FirstOrDefault was not handled well by MongoDB for me. I changed to be an array index var update = Builders<Movie>.Update.Set(movie => movie.Movies[0].MovieName, "Star Wars: A New Hope"); Note: This is in Asp.Net 5 using MongoDB.Driver 2.2.0.
Full Example
public static void TypedUpdateExample() {
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collection = database.GetCollection<Movie>("samples");
//Create some sample data
var movies = new Movie {
Name = "TJ",
Movies = new List<MovieData>
{
new MovieData {
MovieName = "Star Wars: The force awakens"
}
}
};
collection.InsertOne(movies);
//create a filter to retreive the sample data
var filter = Builders<Movie>.Filter.Eq("_id", movies.Id);
//var update = Builders<Movie>.Update.Set("name", "A Different Name");
//TODO:LP:TSTUDE:Check for empty movies
var update = Builders<Movie>.Update.Set(movie => movie.Movies[0].MovieName, "Star Wars: A New Hope");
collection.UpdateOne(filter, update);
}
public class Movie {
[BsonId]
public ObjectId Id { get; set; }
public string Name { get; set; }
public List<MovieData> Movies { get; set; }
}
public class MovieData {
[BsonId]
public ObjectId Id { get; set; }
public string MovieName { get; set; }
}
I am creating a new ViewModel that tally's up the results of a survey, performers some calculations on that data, and then returns the new calculation to a view. I cannot figure out how to include regular "string" data in the collection.
var data = from SurveyResponseModel in db.SurveyResponseModels
group SurveyResponseModel by SurveyResponseModel.MemberId into resultCount
select new ResultsViewModel()
{
MemberId = resultCount.Key,
UseNewTreatmentResult = db.SurveyResponseModels.Count(r => r.UseNewTreatment),
UseBetterTechniqueResult = db.SurveyResponseModels.Count(r => r.UseBetterTechnique),
ChangesOthersResult = db.SurveyResponseModels.First(r => r.ChangesOthers),
};
return View(data);
The first part is counting boolean responses and passing them as an integer back to the ViewModel. The section that includes ChangesOthersResult = db.SurveyResponseModels.First(r => r.ChangesOthers), Should just select the strings from the Model and pass to the ViewModel. I am currently getting a syntax error about changing from type string to bool. I'm not sure what the syntax for this is.
public class SurveyResponseModel
{
[Key]
public int ResponseId { get; set; }
public int MemberId { get; set; }
public int ProgramId { get; set; }
[DisplayName("Use a new treatment")]
public bool UseNewTreatment { get; set; }
[DisplayName("Use better/more updated technique")]
public bool UseBetterTechnique { get; set; }
[DisplayName("Other (please specify):")]
public string ChangesOthers { get; set; }
}
public class ResultsViewModel
{
public int MemberId { get; set; }
public int ProgramId { get; set; }
[DisplayName("Use a new treatment")]
public int UseNewTreatmentResult { get; set; }
[DisplayName("Use better/more updated technique")]
public int UseBetterTechniqueResult { get; set; }
[DisplayName("Other (please specify):")]
public string ChangesOthersResult { get; set; }
}
You need:
ChangesOthersResult = db.SurveyResponseModels.Select(r => r.ChangesOthers)
Or SelectMany. Eventually add FirstOrDefault() at the end depending on what type ChangesOthersResult is and what you actually want to select.
Select gives you a "collection of collections" (I am assuming that ChangesOthers is a collection type). SelectMany a "flattened collection" of the generic type of your ChangesOthers collection. Adding FirstOrDefault() after Select gives you the single collection of the first SurveyResponseModels entity - or null.
Edit
After you supplied the classes I see that ChangesOthers and ChangesOthersResult aren't collections but just of type string. So the line should be:
ChangesOthersResult = db.SurveyResponseModels.Select(r => r.ChangesOthers)
.FirstOrDefault()