FirstOrDefault on List not working - asp.net-mvc

I have a list like
var listDataDemo = model.Jobs.ToList();
The listDataDemo has data like following
Count = 13
[0]: {PaymentItemModel}
when i type in Immediate Window like
listData.FirstOrDefault()
it gives result
Amount: 0
Date: {1/01/0001 12:00:00 AM}
Method: "PayPal"
PayerName: null
PayerNumber: null
PaymentDetailType: Payment
TransactionId: null
But when i write(code in my class)
var demoVal = listData.FirstOrDefault(p=>p.Method=="PayPal")
The name 'demoVal' does not exist in the current context(no value)
How to get a value from LIST.
Please help me.

The below code is working fine for me. Just have a look:
List<test> testList = new List<test>();
testDB testObj = new testDB();
testList = testObj.fn_getAll();
var abc = testList.FirstOrDefault(a => a.Id == 3);
And you just try to change the name of the variable, this might be causing the issue.
I hope it will help you.. :)

Off the cuff, the predicate you're providing to FirstOrDefault to filter results looks like it has a syntax error: (p=>p.Method="PayPal") should be (p=>p.Method=="PayPal").
Granted this was probably a typo, for completeness:
'=' is an assignment operator, for when you want to assign a value to a variable.
'==' is an equality comparison operator, for when you want to test equality between values and get 'true' or 'false'.
Edited to answer beyond the typo...
Are you using Entity Framework?
EF has extension methods for FirstOrDefault also, except the filter parameter is an SQL query. If you're using EF, then you could be missing the following:
using System.Collections.Generic;
using System.Linq;

It looks like the predicate in your call to FirstOrDefault has a typo. You want == for comparison, not = for assignment.

Related

Assigning Value to StringValue In F#

I am working though this example of the Open XML SDK using F#
When I get to this line of code
sheet.Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart)
I am getting a null ref exception when I implement it like this:
sheet.Id.Value <- document.WorkbookPart.GetIdOfPart(worksheetPart)
Is there another way to assign that value? System.Reflection?
I got it working like this:
let sheet = new Sheet
(
Id = new StringValue(spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart)),
SheetId = UInt32Value.FromUInt32(1u),
Name = new StringValue("mySheet")
)
If You want to take a look to the entire sample translated to F#, it's here.
To clarify what's going on, the problem is that sheet.Id is initially null. If we look at the following:
sheet.Id.Value <- document.WorkbookPart.GetIdOfPart(worksheetPart)
The code tries to access the sheet.Id and invoke its Value property setter, but the Id itself is null. The answer posted by Grzegorz sets the value of the whole Id property - it's done in a construtor syntax, but it's equivalent to writing the following:
sheet.Id <- new StringValue(spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart))
This sets the whole Id property to a new StringValue instance.

Appending elements to an array

Hi all real newbie question here.
I have an array like this:
var daysInMonth = Array<([MyCustomClass], NSDate)>()
How can I append an element to this?
I am having difficulty doing so. Trying something like this:
daysInMonth.append([MyCustomClass](), someDate)
or
daysInMonth.append( ([MyCustomClass](), someDate) )
will not work (i'd like to add an empty array initial above of type MyCustomClass, as well as some date that I have) but these are failing (error missing parameter #2 in call)
Any thoughts on what I am lacking in my syntax?
Thanks!
It looks like a swift bug to me. The swift compiler cannot correctly parse the "( (...) )" as passing in a tuple to a function.
If I break the append operation into two statements, it works.
var daysInMonth = Array<([MyCustomClass], NSDate)>()
let data = ([MyCustomClass()], NSDate()) // assuming MyCustomClass init() taks no parameter
daysInMonth.append(data)
note: It was [MyCustomClass]() in your question, which is incorrect.
Try declaring your array using the newer Array syntax instead:
var daysInMonth = [([MyCustomClass], NSDate)]()
Then, this works:
daysInMonth.append(([MyCustomClass](), NSDate()))

loop through model in mvc razor code behind

I am working on MVC4 App, and I am stuck at one point, I tried using google to help me, but without success. This might be more simple then I think, but coming from web forms and shifting to mvc is "painful" sometime.
I am trying to loop through the model I have and get the values stored in that model. I tried few approaches but I am getting an error everytime. This is what I have:
var modelAgentFilter = from s in _aa.Agents
where s.COUNTER == Convert.ToInt32(AgentID)
select s;
if (modelAgentFilter != null)
{
ViewBag.FirstName = // Get FirstName object here
}
Thanks in advance for your comments.
Laziale
EDIT:
I did include for loop like this:
if (modelAgentFilter != null)
{
foreach (var property in modelAgentFilter)
{
string test = property.ADDRESS;
}
}
But when the compiler will reach the foreach step I am getting this error: "LINQ to Entities does not recognize the method 'Int32 ToInt32(System.Object)' method, and this method cannot be translated into a store expression."
I can get to the properties of the var model using that foreach look but as soon as the compiler will try to loop the model that error pops up.
Thanks again
LINQ to Entities does not recognize any methods. You can't use even ToString() in LINQ expression. You need first convert your value and than add it in LINQ.
In your example you need to do something like following:
var _agentID = int.Parse(AgentID);
var modelAgentFilter = from s in _aa.Agents
where s.COUNTER == _agentID
select s;

EF 4.0 : Include based on condition

I have the following Linq Expession being used in EF 4
var map = model.CDM_SubsidiaryDocumentMap.Where(m => m.SubsidiaryID == subsidiaryID)
.Include("CDM_DocumentType")
.Include("CDM_DocumentType.CDM_DocumentHeader")
**(Need Help here) Filter based on CDMDocumentType.CDM_DocumentHeader.ContactID == 123**
.OrderBy(m => m.UISortOrder)
.ToList();
How do I write the missing statement above, where in I include the nested child based on contactID filter. Also note that CDM_DocumentType.CDM_DocumentHeader is a collection. Much appreciated
If you don't mind using the from syntax. Try something like this:
var map = (from m in model.CDM_SubsidiaryDocumentMap
from dmh in m.CDM_DocumentType.CDM_DocumentHeader
where m.SubsidiaryID == subsidiaryID
&& dmh.ContactID == 123
order by m => m.UISortOrder
select m).ToList();
If that doesn't work show more of your Entity Model, as I made and assumtion that CDM_DocumentType is a navigation property on CDM_SubsidiaryDocumentMap.

Problem creating an Entity object/queryable from the result of a LINQ join in MVC

I'm attempting to write a search function for a database table that needs to access information from related tables using Entity Framework. However, I'm running into problems getting the data back out of my initial query after doing a join on the parent table and the related tables. My code currently looks like this. I initialize my queryable object
IQueryable<PurchaseOrder> po = _context.PurchaseOrders;
Where PurchaseOrder is an Entity type. Then there is a series of blocks like this.
if (!String.IsNullOrEmpty(searchViewModel.Comment)){
var helper = _context.PurchaseOrderComments.Where(x => x.CommentText.Contains(searchViewModel.Comment));
var mid = po.Join(helper, r => r.PurchaseOrderID, u => u.PurchaseOrderID, (r, u) =>
new
{
PurchaseOrderID = r.PurchaseOrderID,
PurchaseOrderNumber = r.PurchaseOrderNumber,
VendorID = r.VendorID,
ContractNumber = r.ContractNumber,
BuyerUserID = r.BuyerUserID
});
po = mid.Select(x => new PurchaseOrder
{
PurchaseOrderID = x.PurchaseOrderID,
PurchaseOrderNumber = x.PurchaseOrderNumber,
VendorID = x.VendorID,
ContractNumber = x.ContractNumber,
BuyerUserID = x.BuyerUserID
});
}
After each block, po is passed to the next search parameter. However, as you might guess, my program complains that I can't build a complex type in mid's Select statement. I've also tried building PurchaseOrder objects from the contents of mid, inserting them into a new List of PurchaseOrders, and converting that list into a queryable to assign to po to pass on to the next block. However, that changes po's data type from System.Data.Object.ObjectSet to System.Collections.Generic.List, which then throws an InvalidOperationException the next time I try and iterate through it using a foreach.
So my question is, are there any obvious mistakes in my approach or any suggestions for other ways to approach the problem? Thanks very much for any help.
I think you're making this more complicated than it needs to be. If I understand what you're trying to do, you should be able to do something like this:
if (!String.IsNullOrEmpty(searchViewModel.Comment)){
po = po.Where(
o => o.PurchaseOrderComments.Any(
c => c.CommentText.Contains(searchViewModel.Comment)));
}
StriplingWarrior's solution is the best way. In case that your PurchaseOrder class really doesn't have a navigation collection of PurchaseOrderComments (which would force you to use a join) the following should work and is simpler as your double projection:
po=po.Join(helper, r => r.PurchaseOrderID, u => u.PurchaseOrderID, (r, u) => r);

Resources