Linq: the linked objects are null, why? - ado.net

I have several linked tables (entities). I'm trying to get the entities using the following linq:
ObjectQuery<Location> locations = context.Location;
ObjectQuery<ProductPrice> productPrice = context.ProductPrice;
ObjectQuery<Product> products = context.Product;
IQueryable<ProductPrice> res1 = from pp in productPrice
join loc in locations
on pp.Location equals loc
join prod in products
on pp.Product equals prod
where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1
select pp;
This query returns 2 records, ProductPrice objects that have linked object Location and Product but they are null and I cannot understand why. If I try to fill them in the linq as below:
res =
from pp in productPrice
join loc in locations
on pp.Location equals loc
join prod in products
on pp.Product equals prod
where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1
select new ProductPrice
{
ProductPriceId = pp.ProductPriceId,
Product = prod
};
I have the exception "The entity or complex type 'PBExplorerData.ProductPrice' cannot be constructed in a LINQ to Entities query"
Could someone please explain me what happens and what I need to do?
Thanks

The answer to your first question the Product and Location are null because you need to add an Include("") to your query.
IQueryable<ProductPrice> res1 = from pp in
productPrice.Include("Location").Include("Product")
join loc in locations
on pp.Location equals loc
join prod in products
on pp.Product equals prod
where prod.Title.ToLower().IndexOf(Word.ToLower()) > -1
select pp;
The second issue is EF is trying to push down your query and ProductPrice (is not an entity) so it can not. If you want to do this convert it to an anonymous type so just do
select new
{
ProductPriceId = pp.ProductPriceId,
Product = prod
};
And then do
res.ToList().ConvertAll(x=new ProductPrice () {
ProductPriceId = x.ProductPriceId ,
Product = x.Product
});
Or you could do it other ways, by selecting the entity you want, and just populating manual.

Related

Flutter sqflite, retreiving data from a rawQuery

I have the following rawQuery
final maps = await db.rawQuery("""
select r.id, r.name, r.description,r.created_by,
a.id,a.name,a.description from Resources r
left join Resource_Attribute ra on ra.resource_id = r.id
left join AttributeItems a on ra.attribute_id=a.id
""");
My question is how do I retrieve the data from all the columns in my query? Doing the following
maps.forEach((dbItem){
String resourceId = dbItem["r.id"];
doesn't seem to work. dbItems is a map but contains only the four columns in the Resources table. dbItem["r.id"] returns a null.
dbItems does contain a "row" field which is an array with all the field. Is there way to access that?
If you look at dbItem.keys, you will see that it is ['id','name',...] not ['r.id','r.name'].
You can access your resource id using:
var resourceId = dbItem['id'] as String;
You can name a column explicitely using AS. For example:
var resultSet = await db.rawQuery("SELECT r.id AS r_id FROM test r");
// Get first result
var dbItem = resultSet.first;
// Access its id
var resourceId = dbItem['r_id'] as String;
As alextk suggested , I changed my query to
select r.id as resource_id, r.name as resource_name, r.description as resource_descr,r.created_by as resource_created_by,
a.id as attribute_id,a.name as attribute_name,a.description as attribute_descr from Resources r
left join Resource_Attribute ra on ra.resource_id = r.id
left join AttributeItems a on ra.attribute_id=a.id
and that did the trick.

EF core .any not filtering results

I have the following sql, which I'm trying to translate to linq:
SELECT *
FROM [Service] s
inner join vendor v on vendorid=v.id
inner join VendorLocation vl on vl.VendorId=v.id
where s.active=1 and v.active=1 and vl.City = 'toronto' and vl.Active=1
I have a Service that belongs to a Vendor and the Vendor has Locations. I'm trying to filter the locations based on city, but the query returns results that don't satisfy the conditions in the ".Any" clause
var service = await _context.Service
.Where(s => s.Active && s.Vendor.Active)
.Include(s => s.Vendor)
.ThenInclude(s => s.VendorLocations)
.Where(s => s.Vendor.VendorLocations.Any(l => l.City == City && l.Active))
.ToListAsync();
The sql statement returns the correct results but the linq is not.
Any help is appreciated, thanks! Ben
You can try with query notation:
var query = from v in _context.Vendors
join s in v.Services on v.Id equals s.VendorId
join l in v.ServiceLocations on v.Id equals l.VendorId
where v.Active && s.Active && l.City=="Toronto"
select new {v,s,l};
var result= await query.ToLinqAsync();
Hi your using EF Core now , But
I suggest Use LINQ because its simplest
Please read this page for more
and this is sample code
var innerGroupJoinQuery2 =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
from prod2 in prodGroup
where prod2.UnitPrice > 2.50M
select prod2;
the query returns results that don't satisfy the conditions in the ".Any" clause
Those queries just aren't the same. The SQL Query returns one row per VendorLocation with additional columns from joined tables, and projects all the columns.
SELECT *
FROM [Service] s
inner join vendor v on vendorid=v.id
inner join VendorLocation vl on vl.VendorId=v.id
where s.active=1 and v.active=1 and vl.City = 'toronto' and vl.Active=1
In LINQ this would be something like
from vl in VendorLocation
where vl.Vendor.Active
&& vl.Vendor.Service.Active
&& vl.Active
&& vl.City = 'toronto'
select new
{
ServiceName = vl.Vendor.Service.Name,
ServiceDescription = vl.Vendor.Service.Description,
. . .
VendorName = vl.Vendor.Name,
VendorWhatever = vl.Vendor.Whatever,
. . .
vl.Name,
. . .
};

Linq order by using query expression

Is it possible to do orderby expression using linq query expression based on dynamic string parameter? because the query i have is producing weird SQL query
my linq:
var product = from prod in _context.Products
join cat in _context.Categories on prod.CategoryId equals cat.CategoryId
join sup in _context.Suppliers on prod.SupplierId equals sup.SupplierId
orderby sortParam
select new ProductViewModel
{
ProductName = prod.ProductName,
ProductId = prod.ProductId,
QuantityPerUnit = prod.QuantityPerUnit,
ReorderLevel = prod.ReorderLevel,
UnitsOnOrder = prod.UnitsOnOrder,
UnitPrice = prod.UnitPrice,
UnitsInStock = prod.UnitsInStock,
Discontinued = prod.Discontinued,
Category = cat.CategoryName,
Supplier = sup.CompanyName,
CategoryId = cat.CategoryId,
SupplierId = sup.SupplierId
};
where var sortParam = "prod.ProductName"
The code above produces weird sql where order by sortParam is being converted to (SELECT 1). Full query catched by sql profiler below:
exec sp_executesql N'SELECT [prod].[ProductName], [prod].[ProductID], [prod].[QuantityPerUnit], [prod].[ReorderLevel], [prod].[UnitsOnOrder], [prod].[UnitPrice], [prod].[UnitsInStock], [prod].[Discontinued], [cat].[CategoryName] AS [Category], [sup].[CompanyName] AS [Supplier], [cat].[CategoryID], [sup].[SupplierID]
FROM [Products] AS [prod]
INNER JOIN [Categories] AS [cat] ON [prod].[CategoryID] = [cat].[CategoryID]
INNER JOIN [Suppliers] AS [sup] ON [prod].[SupplierID] = [sup].[SupplierID]
ORDER BY (SELECT 1)
OFFSET #__p_1 ROWS FETCH NEXT #__p_2 ROWS ONLY',N'#__p_1 int,#__p_2 int',#__p_1=0,#__p_2=10
I'm seeing a lot of people doing linq order by using dynamic parameter but all of them use lambda not query expression, please enlighten me
As was already mentioned, you are passing a string value instead of an expression that reflects the column name. There are options for what you want however, see for example here.

how to flatten out webapi EF using DTO and linq

I am trying to flatten out my webapi EF using a DTO and linq but not quite sure how to do it. My end goal is to say, I want to return ALL four accounts where USERNAME = x.
In this example there is 1 username with access to 1 client, and that 1 client has 4 accounts.
How can I make the result come back with 4 entries, 1 for each account?
Here is what I have so far...
var x2 = from b in db.AspNetUsers
where b.UserName == username
select new AspNetUserDetailDTO()
{
UserName = b.UserName,
Email = b.Email,
Mapping_UserClient = b.Mapping_UserClient
//ClientName = b.Mapping_UserClient.SelectMany<Mapping_UserClient>(x => x.ClientID)
//Mapping_UserClient = b.Mapping_UserClient
};
below is my sql diagram.
so I tried writing a plain sql query to return a basic result of what I am looking for... now I do not know how to do this in LINQ
SELECT
dbo.Clients.ClientName
,dbo.Mapping_UserClient.ClientID
,*
FROM [xxx].[dbo].[AspNetUsers]
inner join dbo.Mapping_UserClient on dbo.Mapping_UserClient.AspNetUsersID = dbo.AspNetUsers.Id
inner join dbo.Clients on dbo.Clients.ClientID = dbo.Mapping_UserClient.ClientID
inner join dbo.Mapping_ClientAccount on dbo.Mapping_ClientAccount.ClientID = dbo.Clients.ClientID
inner join dbo.Accounts on dbo.Accounts.AccountID = dbo.Mapping_ClientAccount.AccountID
where Email = 'dddd'
Translating your query above, you would get something like this in Linq:
var query = (from acc in db.Accounts
join mca in db.Mapping_ClientAccount
on acc.AccountId equals mca.ClientID
join cli in db.Clients
on mca.ClientID equals cli.ClientID
join muc in db.Mapping_UserClient
on cli.ClientID equals muc.ClientID
join anu in db.AspNetUsers
on muc.AspNetUsersID equals anu.Id
where anu.UserName == username
select new AspNetUserDetailsDTO()
{
ClientName = cli.ClientName,
ClientID = cli.ClientID
}).ToList();

How to translate SQL into Lambda for use in MS Entity Framework with Repository pattern usage

For example take these two tables:
Company
CompanyID | Name | Address | ...
Employee
EmployeeID | Name | Function | CompanyID | ...
where a Company has several Employees.
When we want to retrieve the Company and Employee data for a certain Employee, this simple SQL statement will do the job:
SELECT e.name as employeename, c.name as companyname
FROM Company c
INNER JOIN Employee e
ON c.CompanyID = e.CompanyID
where e.EmployeeID=3
Now, the question is how to translate this SQL statement into a 'lambda' construct. We have modelled the tables as objects in the MS Entity Framework where we also defined the relationship between the tables (.edmx file).
Also important to mention is that we use the 'Repository' pattern.
The closest I can get is something like this:
List<Company> tmp = _companyRepository.GetAll().Where
(
c.Employee.Any
(
e => e.FKEngineerID == engineerId && e.DbId == jobId
)
).ToList();
Any help is very much appreciated!
This should do, assuming your repositories are returning IQueryables of the types
var list = (from c in _companyRepository.GetAll()
join e in _employeeRepository.GetAll() on c.CompanyId equals e.CompanyId
where e.FKEngineerID == engineerId && e.DbId == jobId
select new
{
EmployeeName = e.name,
CompanyName = c.name
}).ToList();
Since you are constraining the query to a single employee (e.Employee=3) why don't you start with employees.
Also, your sql query return a custom set of columns, one column from the employee table and the other column from company table. To reflect that, you need a custom projection at the ef side.
var result = _employeeRepository.GetAll()
.Where( e => e.DbId == 3 ) // this corresponds to your e.EmployeeID = 3
.Select( e => new {
employeename = e.EmployeeName,
companyname = e.Company.CompanyName
} ) // this does the custom projection
.FirstOrDefault(); // since you want a single entry
if ( result != null ) {
// result is a value of anonymous type with
// two properties, employeename and companyname
}