linq to entities decimal null values from outer join - entity-framework-4

LINQ giving an error while using the below linq
var data = (from p in _context.Products
from invp in _context.Inventories
.Where(inv=>inv.Product.ID== p.ID)
.DefaultIfEmpty()//left outer join
select new { p.ID, p.Name, p.BarCode, p.ProductCategory, p.MRP, p.RetailPrice,stock=invp.Stock } ).ToList() ;
The cast to value type System.Decimal failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
If I remove invp.stock from the select it is working , how can I default invp.stock to 0 if it is null.

You may select like this:
replace
stock=invp.Stock
with
stock=invp.Stock ?? 0

There is nullable decimal and we need to cast them then only it can take the database null to c#
Stock = (decimal?)invp.Stock

Related

left join query in MVC

I have added this code in my controller where I am left joining on 2 tables to stored result in lettergroup variable.
var lettergroup = (from e in opsdb.Queue2
join a in opsdb.QIncidents on e.QID equals a.QID into ps
from ad in ps.DefaultIfEmpty()
select new { ad.IncidentID, ad.TaxTypeID, ad.TaxPeriod, ad.StateID, ad.IncidentDate, e.CustomerID, e.DocumentID }).ToList();
I get this error:
The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
Please help me out with left join query in ASP.NET MVC
try this
var lettergroup = (from e in opsdb.Queue2
join a in opsdb.QIncidents on e.QID equals a.QID into ps
from a in ps.DefaultIfEmpty()
select new { IncidentId= a.IncidentID, TaxTypeID=a.TaxTypeID,
TaxPeriod= a.TaxPeriod, StateID= a.StateID, IncidentDate= a.IncidentDate,
CustomerID=e.CustomerID,DocumentID =e.DocumentID }).ToList();

How to deal with Null Values in OUTER JOINS using Entity Framework 6

I need to process the query at the bottom of this post in C#. The query works, but I don't know how to use it in EF6. I used a method and a viewmodel for it (variable query = the query below). But when it encounters null values in the OUTER JOIN, int32 cant accept this value when calling .toList(). What's the best way to deal with it?
var result = context.Database.SqlQuery<TourQueryViewModel>(query);
var reslist = result.ToList();
I tried my first steps with LINQ, but I dont get it how to translate into LINQ itself or the query-methods, that are equivalent to it. So I am hoping for your help.
SELECT toursdata.TourId AS TourId, toursdata.Tourname AS Tourname,toursdata.Tourdate Tourdate,
toursdata.VehicleId AS VehicleId, toursdata.VehicleName AS VehicleName, toursdata.LicenseNumber AS LicenseNumber,
Employees.EmployeeId AS EmployeeId, Employees.Gender AS Gender, Employees.Forename AS Forename, Employees.Surname AS Surname
FROM (
SELECT te.TourId, te.Tourname, te.Tourdate,
Vehicles.VehicleId, Vehicles.VehicleName, Vehicles.LicenseNumber,
TourEmployees.EmployeeId
FROM TourEmployees RIGHT OUTER JOIN Tours AS te ON TourEmployees.TourId = te.TourId,
Tours AS tv INNER JOIN Vehicles ON tv.VehicleId = Vehicles.VehicleId
WHERE tv.TourId = te.TourId
) toursdata
LEFT OUTER JOIN Employees ON toursdata.EmployeeId = Employees.EmployeeId
To eliminate the null problem, I changed the data type of the corresponding entity-attribute to a nullable-type
int turned to int?.
Didnt know about that language feature.

Entity Framework Syntax for IN clause with subquery

I want a Entity Framework sql syntax for IN clause with subquery..
My original syntax is like
Select * from Table1 where Table1.id in (select table2.id from Table2 where 1=1)
I tried to write this like below:
"SELECT VALUE pkg_outer from
(SELECT distinct(pkg) from ExploitaEntities.mst_package as pkg WHERE 1=1
AND pkg.package_id in
(SELECT VALUE dtl_outer FROM(select distinct(dtl.package_id) from ExploitaEntities.mst_pkg_detail as dtl where 1=1))
as dtl_outer)
as pkg_outer"
but it is giving me error as below:
"The element type 'Edm.Int32' and the CollectionType 'Transient.collection[Transient.rowtype[(package_id,Edm.Int32(Nullable=True,DefaultValue=))](Nullable=True,DefaultValue=)]'
are not compatible. The IN expression only supports entity, primitive, and reference types.
Near IN set expression,..."
dbContext.TableName.Where(x => x.ColumnName.Value == "Test")
Reference the Table in your Db context. You can set a condition for every record that is read.

Breeze query returning null value for columns that does contain data in datatabase

var query = EntityQuery.from('Cases')
.where("ID", "==", id);
When I try to execute the above query for an ID value, it returns null value for 2 columns and the record in the table does contain values for it. The columns are string.
return datacontext.getCase(caseID, vm.caseObj).then(function () {
alert(vm.caseObj().AuditTypeCd());
});
caseID is a global variable which contains the desired ID. If I replace that with a constant value of any ID (10 or any other ID), I see that the property AuditTypeCd is fetched.
The query returns null value for few columns when global variable caseID is used. A very strange behavior.

LINQ to entity, wrong join type

I have a query that looks like so....
var q = Dal.TBLINVENTORies.Where(i => i.SHOWIT);
q = q.Where(i => i.dtStart < DateTime.Now || i.dtStart == null);
q = q.Where(i => i.dtEnd > DateTime.Now || i.dtEnd == null);
q = q.Where(i => i.sSystem.Contains("OE"));
q = q.Where(i => i.WS_ActiveList_ID == 0 || i.tblWS_ActiveList.WS_MasterList_ID == 16);
var test2 = q.ToList();
Immediately before the "ToList()", if I examine the query, I get the following sql (more or less)
SELECT [Extent1].*
FROM [dbo].[TBLINVENTORY] AS [Extent1]
INNER JOIN [dbo].[tblWS_ActiveList] AS [Extent2] ON [Extent1].[WS_ActiveList_ID] = [Extent2].[ID]
WHERE ([Extent1].[SHOWIT] = 1)
AND (([Extent1].[dtStart] < CAST( SysDateTime() AS datetime2)) OR ([Extent1].[dtStart] IS NULL))
AND (([Extent1].[dtEnd] > CAST( SysDateTime() AS datetime2)) OR ([Extent1].[dtEnd] IS NULL))
AND ([Extent1].[sSystem] LIKE '%OE%')
AND ([Extent1].[WS_ActiveList_ID] = 0 OR [Extent2].[WS_MasterList_ID] = 16)
Unfortunately, this is not what I need, because relationship between "Inventory" and "ActiveList" is not really 1-to-Many, but Zero-to-Many (I'm not sure I'm using the correct terms). Basically, An inventory item might or might not have a related "ActiveList".
If I change that raw SQL to use a LEFT OUTER JOIN, instead of an INNER JOIN, the SQL returns the values I expect.
What is needed to force the LEFT OUTER JOIN?
I've tried the recommended solution from Linq to entities - One to many relationship - need left outer join instead of cross join , but,
var q2 = from inv in Dal.TBLINVENTORies from al in inv.tblWS_ActiveList
returns an error:
Error 65 An expression of type 'xxxx.DAL.tblWS_ActiveList' is not allowed in a subsequent from clause in a query expression with source type 'System.Data.Entity.DbSet<xxxx.DAL.TBLINVENTORY>'. Type inference failed in the call to 'SelectMany'.
I wonder if my link/relationship is constructed incorrectly? Any other ideas?
Thanks!
EDIT :: Additional Data
-- create foreign key, but don't enforce on existing values
ALTER TABLE [dbo].[tblInventory] --the ONE Table
WITH NOCHECK
ADD CONSTRAINT [FK__tblInventory.WS_ActiveList_ID__tblWS_ActiveList.ID]
FOREIGN KEY([WS_ActiveList_ID])
REFERENCES [dbo].[tblWS_ActiveList] ([ID]) --the MANY Table
NOT FOR REPLICATION
GO
-- disable enforcement of the foreign key, but leave it in place (virtual key)
ALTER TABLE [dbo].[tblInventory]
NOCHECK CONSTRAINT [FK__tblInventory.WS_ActiveList_ID__tblWS_ActiveList.ID]
GO
and the definition of WS_ActiveList_ID:
[WS_ActiveList_ID] [int] NOT NULL CONSTRAINT [DF_TBLINVENTORY_WS_ActiveList_ID] DEFAULT (0),
Your main problem is that you've turned off the referential integrity checks in your database.
Apart from the obvious problem of bad data, this won't work with EF.
By far the best option is to make WS_ActiveList_ID nullable, update your data to change all the 0s to NULLs and turn the constraint back on.
If you can't do that, I think you'll have to generate a SQL statement as a string and execute it with dbContext.Database.SqlQuery<T> ( MSDN )

Resources