getting values from a table where value is not null - linq

When doing an EF query in the code behind using LINQ, how does one go about retrieving only those items in a nullable column that actually have data?
for example;
Dim unit = (From d in ctx.Inventories
Where d.ProductId Is Not Null
Select d).ToList()
Where obviously that query doesnt work, how does one go about this?

Since ProductId is likely a nullable type, you should be able to do:
Dim unit = (From d in ctx.Inventories
Where d.ProductId.HasValue
Select d).ToList()

Related

How to ignore nullable value during dynamic Linq GroupJoin on Nullable<int> Column?

We are using below code for dynamic groupjoin on SecurityID integer Column
but it includes the resultset with with nullable values.
var innerJoin = source.AsQueryable().GroupJoin(destination.AsQueryable(),
"new (outer.SecurityId as SecurityId)",
"new (inner.SecurityId as SecurityId)",
"new (outer as sources, group as destinations)").
SelectMany("destinations", "new(outer.sources as sources, inner as destinations)");
We want to avoid null values from the above query. The above query performs innerjoin and is working fine if we have joins on string columns.
Please help us to achive the above query to perform inner join on integer columns which may have 'null' values.
First of all, you can not assign null to int, instead you need to use Nullable<int> / int?. If that's the case then just filter your source using Where clause and then perform GroupJoin. I think that is the easiest way.

HQL Select New doesn't return row when a foreign key is null

I have the following named query
#NamedQuery(name = "UserFlight.getUserFlightDetails",
query = "SELECT new com.foobar.UserFlightDetails(uf.flight.divertedAirport, uf.flight.number) " +
"FROM UserFlight uf WHERE uf.user.id=?1 AND uf.flight.id=?2")
The UserFlightDetails constructor is as follows
public UserFlightDetails(Airport airport, String flightNumber) {
this.setDivertedAirport(airport);
this.setFlightNumber(flightNumber);
}
divertedAirport is a foreign key in the flight table, path=(uf.flight.divertedAirport)
My problem is when divertedAirport is null (it's a nullable foreign key), my HQL query returns null as the result (The code doesn't even trigger the constructor above), so I don't get the flightNumber which is never null.
If the divertedAirport isn't null, I get both the airport and the flight number fine (and the above constructor gets executed just fine).
What could be causing this and how could I resolve it? I tried some null functions like nullif and coalesce but nothing helped.
I'm using spring boot 1.2.7, hibernate-core 4.3.11.Final
Probably, the problem is the uf.flight.divertedAirport. This expression do a JOIN between flight and divertedAirport but, as you say, divertedAirport is a fk and can be null.
So, you need to use the LEFT JOIN.
I would rewrite your query like this:
#NamedQuery(name = "UserFlight.getUserFlightDetails",
query =
"SELECT new com.foobar.UserFlightDetails(divertedAirport, flight.number)
FROM UserFlight uf
JOIN uf.flight flight
LEFT JOIN flight.divertedAirport divertedAirport
JOIN uf.user user
WHERE user.id = ?1 AND flight.id = ?2 ")
I remove the references like uf.user.id for a explicit JOIN (JOIN uf.user user plus user.id), because is more legible and this kind of problem that generated your question is more easy to find using this way to write JPQL queries.

How to query dataset table on primary key of smallInt using linq C#

Let say I have the following sql table. Customer_id column is a primary key with smallint.
And I am trying to create a linq query, where I want to get all data for customer with id, let say 1.
How to do this.
Already done and not working:
1.
var query = from row in dt.AsEnumerable()
where row.Field<Int32>("customer_id") == Convert.ToInt32(2)
select row;
2.
var query = from row in dt.AsEnumerable()
where row.Field<Int16>("customer_id") == Convert.ToInt16(2)
select row
debug for example 1,2
Syntax error
Exceptions
Why don't you use this:
DataRow needle = hayStack.Tables["Customer"].Rows.Find(2);
Your method should be rewritten as something like this:
private DataRow GetCustomerDetails(Int16 customer_id)
{
return _dt.Tables["Customer"].Rows.Find(customer_id);
}
The calling method would have to check for null beeing returned from the method, since an invalid customer_id would cause Find() tu return null.
Try using short type instead of Int32.

entity framework lazy loading null properties in child

Using entity framwork with lazy loading - Have the following question on loading related entities when the entities
are null.
Say I have two tables employee and employeedetails. Assume in the above case not all employee entries have an entry in the employeedetails table.
If I want to look up a list of Employees
(from e in objectcontext.employees
select new EmployeeEntity
{
EmpID= e.EmployeeID,
FirstName = e.FirstName,
Address = e.employeedetails.Address
}).ToList();
EmployeeEntity is the data class into which we stuff the results.
The above code breaks if even one employee in the returned list
does not have a entry in table employeedetails. This is obvious since e.employeedetails will be null for those customers who do not have a details entry
What is the best way to rewrite the above query?
Would something like this be acceptable ?
(from e in objectcontext.employees
select new EmployeeEntity
{
EmpID= e.EmployeeID,
FirstName = e.FirstName,
Address = e.employeedetails == null ? "" : e.employeedetails.Address,
}).ToList();
I am not clear on the efficiency of this above query - Would this statment do the null check at DB level?
Should I instead do an explicit include like
objectcontext.include("employeedetails")...
And then loop through the results to check for null?
Yes, this statement would indeed perform a null check in the SQL query that is generated. Most likely, it will simply be a NVL or COALESCE.
That's the way you should be doing it.

Adding a random Guid column to a Linq to Entities query to grab random records

I've found some articles about using the RandomView view and the GetNewID function to pull back randomized records, but they are using this method with Linq to SQL which allows Functions and Stored Procs to be used with no return value or a scalar return value. From what I understand, a Stored Proc has to been returned as one of the Entity Framework objects from my generated model. I have been able to get that to work as an object, but not returning a scalar or no return set.
What I want to do is to simply add a column to my Linq query that contains a newly generated Guid so that I can order by the new Guids and take a specific number of records randomly. Can anyone help with some sort of lambda expression or join that would enable me to do this? It seems like it should be something built into EF, but I understand that we are on EF v1.
(Please provide code in VB.net)
In the Select clause of your Linq query, you should be able to insert a GUID like this:
var result = from myRecord in myTable
select new {
field1 = myRecord.field1,
field2 = myRecord.field2,
guidField = Guid.NewGuid()
};
Well, my VB is a little rusty, but I think this will work...
Dim result =
From myRecord in myTable _
Select field1, _
field2, _
guidField = System.Guid.NewGuid()

Resources