How to join the tables in linq to sql? - entity-framework

Table1 :
userid name address
1 venkat srinagr
2 venkatesh sainagar
Table2:
id userid lat lon
1 1 14.000 15.000
2 2 14.3526 15.3698
by passing "venkat" as parameter then need to pull all matching records and his userid,name,lat,lon.
in above table1 "venkat" contains in both rows then need to pull 2 records.how to get userid,name,lat,lon for all matching rows..
for sigle record i am able to get.but there are multiple rows how to get please tell me....

var result = from p in cxt.Table2
where p.Table1.Name.Contains(name)
select new
{
p.Users.User_Id,p.Users.Name,p.Latitude,p.Longitude
};

Im sure someone will say this is not the most effective way but this is how i would do it.
string InputString = "venkat";
var tab =(from a in db.tablea
from b in db.tableb
where a.userid == b.userid && a.name == InputString
select new
{
UserID = a.userid,
Username = a.name,
Latitude = b.lat,
Longditude = b.lon
}).FirstOrDefault();
FirstOrDefault() is only if you want to force only one output or null,
if you want a collection of some sort, then just remove it.

Related

Entity Framework Core Count unrelated records in another table

I need to count how many records in the tableA are not in the tableA, how to do this with LINQ?
with SQL I do the following way
select count(*) as total from produtoitemgrade g
where g.id not in (select idprodutograde from produtoestoque where idProduto = 12)
and g.idProduto = 12
my linq code so far.
var temp = (from a in Produtoitemgrades
join b in Produtoestoques on a.IdUnico equals b.IdUnicoGrade into g1
where g1.Count(y => y.IdProduto == 12)>0 && !g1.Any()
select a).ToList();
I tried to follow that example LINQ get rows from a table that don't exist in another table when using group by?
but an error occurs when running, how can I do this?
Thanks!
Your query should looks like the following, if you want to have the same SQL execution plan:
var query =
from a in Produtoitemgrades
where !Produtoestoques.Where(b => a.IdUnico == b.IdUnicoGrade && b.idProduto == 12).Any()
&& a.idProduto == 12
select a;
var result = query.Count();

Apply join on two result set - Postgres

I have query that gives me the documentid
select documentid from tbldocumentbyclient
where tbldocumentbyclient.isactive = true
and applicationid = '000116'
result:
Another query that give me the following result
SELECT documentcategory,documentcategoryid, string_agg(documentid::text, ',') as documentid
FROM tbldocumentmaster
where accounttype = 1 and usertype= 'INDIVIDUAL'
group by documentcategory,documentcategoryid
order by documentcategoryid;
result :
[![enter image description here][2]][2]
Now,Can someone please suggest me how to get CategoryName that is not associated with any documentid
For Above case my result should be following.
DP Proof - 134 not available in first result
Address Proof Permanent - row 4.. not a single id available in documenid result
Here this are the documentcategory that is not associate with any document id
I think a simple join between your two tables should do the trick. The logic here is if a document category from tbldocumentmaster really has no document IDs which match to anything in the tbldocumentbyclient table then the join should filter it off, leaving behind those categories which do match.
SELECT t1.documentcategory
FROM tbldocumentmaster t1
LEFT JOIN tbldocumentbyclient t2
ON t1.documentid = t2.documentid
WHERE t2.isactive = true AND
t2.applicationid = '000116' AND
t1.accounttype = 1 AND
t1.usertype = 'INDIVIDUAL' AND
t2.documentid IS NULL
try this:
SELECT distinct documentcategory,documentcategoryid
FROM tbldocumentmaster m
LEFT OUTER JOIN tbldocumentbyclient d on d.documentid = m.documentid
where accounttype = 1 and usertype= 'INDIVIDUAL'
and m.documentid is null
and applicationid = '000116'
group by documentcategory,documentcategoryid
order by documentcategoryid;
I have not tested but you can try this query:
SELECT documentcategory,documentcategoryid, string_agg(documentid::text, ',') as documentid
FROM tbldocumentmaster
where accounttype = 1 and usertype= 'INDIVIDUAL' and documentid not in (select documentid from tbldocumentbyclient where tbldocumentbyclient.isactive = true and applicationid = '000116')
group by documentcategory,documentcategoryid
order by documentcategoryid;

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

search the word in linq to sql?

Table users:
userid username
------------------------------------
1 venkatesh duggirala
2 deviprasad
3 dhanu
if user sends username="d" then need to get all records.by using "contains" i am getting 2,3 as result.but 1st record also having "d" in duggirala.
query:
var result = from p in cxt.users
where p.Users.username.Contains(name)
select new
{
p.Userid
};
rewrite your query like this:
var result = from p in cxt.users
where p.Users.username.ToLower().Contains(name.ToLower())
select new
{
p.Userid
};

Linq: the linked objects are null, why?

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.