How to add FirstOrDefault value into cshtml dropdownlist - drop-down-menu

How to add FirstOrDefault value into cshtml dropdownlist?
Controller: Gets First Customer that has CustomerActive == false
CUSTOMERLIST singleCustomer = db.CUSTOMERLIST.FirstOrDefault(s => s.CustomerActive == false);
ViewBag.SingleCustomer= singleCustomer;
CSHTML:
#Html.DropDownList("SingleCustomer", String.Empty)

Actually i think u misunderstood the Use of FirstOrDefault. The Following Example il explain the use of FirstOrDefault
var list = new List<string>() { "cus1", "Cus2", "cus3" };
Console.WriteLine(list.FirstOrDefault());
OutPut:
cus1
It il take First value only.
If u checked with some condition means, a collection is empty, it returns the default value for the type.so it eliminates exceptions.
So Whatever if the checked condition is true or false you il get only one Customer value ,for displaying that value dont try dropdown list .dropdown list is used to display More then one Customers.Go for Textbox or Label .

Related

How to query a child element, present inside a list item

I want to automate the below scenario using Xamarin.UITest:
The List has several rows and each row has different elements inside it.
I want to iterate through the list and find elements inside each row using Xamarin.
IList CellList = app.Query(thisObject => thisObject.Id("MyList_ID"));
foreach(var element in CellList)
{
//Here I want to go inside each row and find an element inside each row. So what needs to be changed in the below line of code?
bool isNTextPresent = (app.Query(thisObject => thisObject.Id("NText_ID")).Length) == 1 ? true : false;
Assert.AreEqual(isNTextPresent , true);
}

object reference not set error in mvc5

i am using viewmodel to display data from two tables (Eta and Voyage) and i have used viewmodel name as 'EtaVoyage'.The problem is when i use this query, it gives me this error
Additional information: Object reference not set to an instance of an object.
var Test = db.Etas.AsEnumerable().Select(v => new EtaVoyage()
{
ShippingAgent = v.ShippingAgent,
VesselInformation = v.VesselInformation,
Port = v.Port,
CPort = v.CPort,
EtaDate = v.EtaDate,
GoodsCarried = v.VoyageDetails.FirstOrDefault().GoodsCarried,
VoyagePurpose = v.VoyageDetails.FirstOrDefault().VoyagePurpose
}).ToList();
return View(Test);
But when i comment the last two fields related to voyagedetails, it is working fine.
var Test = db.Etas.AsEnumerable().Select(v => new EtaVoyage()
{
ShippingAgent = v.ShippingAgent,
VesselInformation = v.VesselInformation,
Port = v.Port,
CustomPort = v.CustomPort,
EtaDate = v.EtaDate,
// GoodsCarried = v.VoyageDetails.FirstOrDefault().GoodsCarried,
// VoyagePurpose = v.VoyageDetails.FirstOrDefault().VoyagePurpose
}).ToList();
return View(Test);
i need to display these two columns too in the index page.
FirstOrDefault() might return null,
Enumerable.FirstOrDefault : Return Value
Type: TSource
default(TSource) if source is empty; otherwise, the first element in source.
Use
.Select(i=>i.GoodsCarried).FirstOrDefault()
....
GoodsCarried = v.VoyageDetails.Select(i=>i.GoodsCarried).FirstOrDefault(),
VoyagePurpose = v.VoyageDetails.Select(i=>i.VoyagePurpose).FirstOrDefault()
}).ToList();
The collection v.VoyageDetails must not contain any items, and therefore FirstOrDefault is returning the default (null for reference types). You can handle this special case separately, or, since you seem to just be flattening a collection, you can use a null-conditional operator to set GoodsCarried and VoyagePurpose to null when FirstOrDefault returns null.
GoodsCarried = v.VoyageDetails.FirstOrDefault()?.GoodsCarried,
VoyagePurpose = v.VoyageDetails.FirstOrDefault()?.VoyagePurpose
Note it is also possible that:
v.VoyageDetails itself is null, depending on how your class is initialized and data is loaded. If this is expected, you may need to handle this case as well. Again with the null-conditional operator:
GoodsCarried = v.VoyageDetails?.FirstOrDefault()?.GoodsCarried,
VoyagePurpose = v.VoyageDetails?.FirstOrDefault()?.VoyagePurpose
If you are using an ORM such as Entity Framework, the VoyageDetails collection is not eagerly loaded, it may simply not be retrieving the data for you. If this applies, you need to explicitly load the data in the collection. In Entity Framework this is done with an Include call. Note your AsEnumerable() call will stop Linq-To-Sql from optimizing this into a single query, but I assume this is intentional:
db.Etas.Include(x => x.VoyageDetails).AsEnumerable().Select(...)

Return value of IEnumerable<T>.Contains changes if called multiple times

I'm having trouble understanding why multiple calls of Contains return different values for the same parameter on the same enumerable.
While I understand that the collection can be modified, thus changing the result in a subsequent call, this can be ruled out here.
Consider the following (stripped-down) code in an MVC view.
The purpose of this will be to display a list of checkboxes (as there's no HTML-helper for that), and determining through the model's properties which ones should be checked when opening the view.
#foreach (var d in Model.AllDomains) {
bool isChecked = Model.Project.Domains.Contains(d.ID);
<input #(isChecked ? "checked=\"checked\" " : "")type="checkbox" value="#d.ID" />
// more stuff here
}
Changing this to use an actual List makes the whole thing work as expected:
var tmp = Model.Project.Domains.ToList();
#foreach (var d in Model.AllDomains) {
bool isChecked = tmp.Contains(d.ID);
<input #(isChecked ? "checked=\"checked\" " : "")type="checkbox" value="#d.ID" />
// more stuff here
}
The following is the model that is bound to my view (again simplified to make it more readable):
public ProjectVM GetByID(int id) {
return new ProjectVM {
Project = new Project {
... // Other properties here
Domains = from d in MyObjectModel.Projects[id].Domains
select d.ID
},
AllDomains = from d in MyObjectModel.Domains
orderby d.Name
select new {
ID = d.ID,
Name = d.Name
}
};
}
Now, while from debugging I know that Model.Project.Domains will contain the correct number of entries, as well as the correct values, calling .Contains() on the method returns an arbitrary result - either true or false.
In fact, if I put the line with the Contains() call into the debugger's "Watch" tab multiple times, even with an hard coded argument (e.g. 4) the result will alternate from true to false with every call.
What is happening here, what am I overlooking?
Because of the way that Model.Project.Domains is instantiated, its actual type is a WhereSelectEnumerableIterator<T>, but this implements IEnumerable<T> so that shouldn't be an issue...
It seems that the root cause of the problem was a sloppy/unusual implementation of the Enumerator in the foundation classes of our object model which made GetEnumerator() return an iterator which was already used in the previous call
Since Contains() stops iterating over the collection after the first match is found, it would return false on such an Enumerator if the seeked value was in the part which had already been searched in the previous iteration.
A negative result of Contains() caused the enumerator to reset internally, which explained the "toggling" result described in my original post.

EF4.1 - Try update many rows

I need to update all rows of my table when user visits one specific page.
All fields need to be updated to "false".
I tried this code:
var history = db.UserHistory.Where(m => m.UserID == id);
TryUpdateModel(history);
history.IsActive = false;
db.SaveChanges();
But it throws me an error message.
Anyone could help me with this update?
I couldn't get at first that LINQ didn`t update many rows at once, I have to make a loop and update each one. My final code is this one:
var history = db.UserHistory.Where(m => m.UserID == id).ToList();
TryUpdateModel(history);
history.ForEach(m => m.IsActive = false);
db.SaveChanges();
Since it seems like you're just selecting a single entry you want to probably want to append .FirstOrDefault() to your first line, which should appear with intellisense.
var history = db.UserHistory.Where(m => m.UserID == id).FirstOrDefault();
TryUpdateModel(history);
history.IsActive = false;
db.SaveChanges();
Right now you're returning an IQueryable as opposed to a single entry. FirstOrDefault will return a single UserHistory entity, so at least you'd be passing a single item to TryUpdateModel.

Getting a column value

private string FindTaxItemLocation(string taxItemDescription)
{
if (!templateDS.Tables.Contains(cityStateTaxesTable.TableName))
throw new Exception("The schema dos not include city state employee/employer taxes table");
var cityStateTaxes =
templateDS.Tables[cityStateTaxesTable.TableName].AsEnumerable().FirstOrDefault(
x => x.Field<string>(Fields.Description.Name) == taxItemDescription);//[x.Field<string>(Fields.SteStateCodeKey.Name)]);
if (cityStateTaxes != null)
return cityStateTaxes[Fields.SteStateCodeKey.Name].ToString();
return null;
}
cityStateTaxes is a DataRow, why/how I cannot get the column value inside FirstOrDefault()?
Thanks,
FirstOrDefault() selects the first item in the collection (optionally that satisfies a predicate) or returns null in the case there it is empty (or nothing satisfies the predicate). It will not do projections for you. So if you use it, it can be awkward to access a field of the item since you must include default value checks.
My suggestion is to always project to your desired field(s) first before using FirstOrDefault(), that way you get your field straight without needing to perform the check.
var cityStateTaxes = templateDS.Tables[cityStateTaxesTable.TableName]
.AsEnumerable()
.Where(row => row.Field<string>(Fields.Description.Name) == taxItemDescription) // filter the rows
.Select(row => row.Field<string>(Fields.SteStateCodeKey.Name)) // project to your field
.FirstOrDefault(); // you now have your property (or the default value)
return cityStateTaxes;

Resources