No result in my result view of Quick watch but the result is under non-public members - linq

in my query when i see quick watch, under the result it returns no result but when go through Non-Public members under source and result in view I see all my results,how can i access to them? and why its like this?im using PostgreSQL for my database
var test = (from t in db.v_vpn_gateway.AsEnumerable()
where t.turbine_id.ToString() == id
select new TurbineDvce
{
Comments = "VPN Gateway",
Description = string.Empty,
DeviceIP = t.vpn_gateway.ToString(),
DeviceType = t.device_type,
FirmwareVersion = string.Empty,
Model = t.model,
Password = string.Empty,
Phone = string.Empty,
Producer = t.producer,
PublicIP = t.vpn_public_ip.ToString(),
TurbineId = t.turbine_id.ToString(),
Username = string.Empty
});

Looks like you need to "Hydrate" the result. The way Linq works with Lazy Evaluation, really you are just getting a place holder back for the test variable, and the actual query will run when the test variable is used by other code. Since you have a "where" clause, you should be expecting back an IEnumerable, so you can add ToList() or ToArray() to the end of your query, which will force the query to run and store the list or array in your test variable. That should give you access to that data right after the query runs.

Related

How do I know if my linq will return a useable object or a null

I am working on a web service. I am using linq to query a database. Seemingly simple, but I've run into an issue. Here is my code for reference:
List<Comment> res = new List<Comment>();
using (ApplicationHistoryEntities ahe = new ApplicationHistoryEntities())
{
res = (from columns in ahe.Comments
where columns.NetforumId == actionuniqueid
select columns).ToList();
}
If I have no entries in the database, will my .ToList() throw an error? I could deploy it, and just try it out but I want to know more about the mechanism that my linq is using. If ahe.Comments database has no rows... what will the (from...) section return?
I could just add a null reference check, use dynamics etc but I want to really understand it.
I found this Q: how to know if my linq query returns null but it seems like all of the answers are in conflict on how it really should be done...
example answers:
Either you can convert it to list and then check the count
Best approach is to check there is null(no items) in list use Any() instead of count()
LINQ queries should never return null and you should not get an exception if the result is empty. You probably have an error in your code.
You can realise the result as a list then check the items.
You can see why I question how it works.
Edit:
Final code looks like this:
List<Comment> res;
using (ApplicationHistoryEntities ahe = new ApplicationHistoryEntities())
{
res = ahe.Comments?.Where(rowItem => rowItem.NetforumId == actionuniqueid).ToList() ??
new List<Comment>().ToList();
}
Look at this example:
List<string> test = new List<string>();
var test1 = test.Where(x => x == "a").ToList();
If test exists but is empty the query returns an empty list. If test is null the query throws an error. So you can adapt the query as follows
List<string> test = new List<string>();
test = null;
var test1 = test?.Where(x => x == "a") ?? new List<string>().ToList();
The query is now 'safe'. Both of the above examples return an empty list i.e. test1.Count() will return zero but will be usable.
You can also look at the definitions of Where and ToList

How do I execute a query that returns true or false if a row exists?

I'm familiar with creating queries like this in my code:
var word = dbcon.Query<Word>("SELECT Correct FROM Phrase WHERE Id = ?", id).FirstOrDefault();
But is there a way I could execute this query and have it return just a true or a false if the value existed or not?
"SELECT Correct FROM Phrase WHERE Id = ?"
Note that I am using SQLite.net so I would be interested in solutions that use that.
You should be able to use the Any() extension method, so like:
var word = dbcon.Query<Word>("SELECT Correct FROM Phrase WHERE Id = ?", id).Any();

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(...)

mvc3 dapper No mapping exists from model

I am doing some coding in dapper and I get the error No mapping exists from object type to a known managed provider native type this error occurs on the myfriends var for dapper . I am using dapper to get a list of INT values from a table then comparing them against another.. this is the code that gives me that error
int myid = Convert.ToInt32(User.Identity.Name);
// The var myfriend is giving me that error above
var myfriends = sqlConnection.Query<friend>("Select otherfriendsID from friends where profileID=#myidd", new { myidd = myid }).ToList();
var profiles = sqlConnection.Query<profile>("Select top 40 * from profiles where photo is not null AND profileID=#friendship order by profileID desc", new {friendship=myfriends}).ToList();
however if I use entity everything works fine for instance this code below works..
var myfriends = (from s in db.friends where s.profileID == myid select s.otherfriendsID).ToList();
What could be going on here..
myfriends is a List<friend>. You then pass that in as a query parameter, i.e.
new {friendship=myfriends}
with:
AND profileID=#friendship
Now... what is #friendship ? How should it pass in a List<friend> here? What does that even mean to pass in a list of objects (each of which could have multiple properties) as a single parameter? (note: I'm ignoring table-valued-parameters for the purposes of this question)
So: how many myfriends do you expect? 0? 1? any number? This could be, for example:
var profileIds = myfriends.Select(x => x.ProfileId);
...
new {profileIds}
...
AND profileID in #profileIds
or maybe:
new {profileId = myfriends.Single().ProfileId}
...
AND profileID = #profileId

How to search with dynamic entity names with linq

Basically all I'm looking to do is something like the following:
string EntityFrameworkType = "Product";
string searchField = "ProductName";
string searchValue = "My Product";
using( var context = new entitycontext())
{
var result = (from x in context.EntityFrameworkType.Where(l=>l.searchField == searchValue) select x).FirstOrDefault();
}
of course this syntax won't work because context does not contain an entity called "EntityFrameworkType"...
Is it possible to do this another way??? What I'm looking to do in generalize my database duplicate check. In this example, I'm searching for any Product with the Name "My Product". But I'd like to be able to pass in these string for say, ProductCategory with ProductCategoryId = 1.... etc...
you can have a look here to get the idea of how it is done.
You'll need to learn about Expression

Resources