Distinct method does not work Entity Framework - c#

How do I get randomly similar data
me tried to merge different ones in the first stage but Different function does not work,
var turler= (from x in db.bird_table_ad
join e in db.kus_resim on x.tr_x equals e.kus_tur
where x.aile == item
select new GozlemTurleri
{
id = x.id,
kod = x.kod,
tr_x = x.tr_x,
en_x = x.en_x,
lt_x = x.lt_x,
turfotourl="image_resize.phpad="+e.altDIR+"/"+e.resim+"&yon="+(e.galeri=="fg"?"2":"HD2"),
aile = x.aile,
gfoto = x.gfoto
}).Distinct().ToList();

If you try to get distinct record with regarding to tr_x from database then you can use GroupBy in entity framework.
So your code will be.
.GroupBy(x => x.tr_x).Select(x => x.First()).ToList();
Instead of
.Distinct().ToList();

Related

Linq Join query returning empty dataset

I am using below code to join two tables based on officeId field. Its retuning 0 records.
IQueryable<Usage> usages = this.context.Usage;
usages = usages.Where(usage => usage.OfficeId == officeId);
var agencyList = this.context.Agencies.ToList();
var usage = usages.ToList();
var query = usage.Join(agencyList,
r => r.OfficeId,
a => a.OfficeId,
(r, a) => new UsageAgencyApiModel () {
Id = r.Id,
Product = r.Product,
Chain = a.Chain,
Name = a.Name
}).ToList();
I have 1000+ records in agencies table and 26 records in usage table.
I am expecting 26 records as a result with chain and name colums attached to result from agency table.
Its not returning anything. I am new to .net please guide me if I am missing anything
EDIT
#Tim Schmelter's solution works fine if I get both table context while executing join. But I need to add filter on top of usage table before applying join
IQueryable<Usage> usages = this.context.Usage;
usages = usages.Where(usage => usage.OfficeId == officeId);
var query = from a in usages
// works with this.context.usages instead of usages
join u in this.context.Agencies on a.OfficeId equals u.OfficeId
select new
{
Id = a.Id,
Product = a.Product,
Chain = u.Chain,
Name = u.Name
};
return query.ToList();
Attaching screenshot here
same join query works fine with in memory data as you see below
Both ways works fine if I add in memory datasource or both datasource directly. But not working if I add filter on usages based on officeId before applying join query
One problem ist that you load all into memory first(ToList()).
With joins i prefer query syntax, it is less verbose:
var query = from a in this.context.Agencies
join u in this.context.Usage on a.OfficeId equals u.OfficeId
select new UsageAgencyApiModel()
{
Id = u.Id,
Product = u.Product,
Chain = a.Chain,
Name = a.Name
};
List<UsageAgencyApiModel> resultList = query.ToList();
Edit: You should be able to apply the Where after the Join. If you still don't get records there are no matching:
var query = from a in this.context.Agencies
join u in this.context.Usage on a.OfficeId equals u.OfficeId
where u.OfficeId == officeId
select new UsageAgencyApiModel{ ... };
The following code can help to get the output based on the ID value.
Of course, I wrote with Lambda.
var officeId = 1;
var query = context.Agencies // your starting point - table in the "from" statement
.Join(database.context.Usage, // the source table of the inner join
agency => agency.OfficeId, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
usage => usage.OfficeId , // Select the foreign key (the second part of the "on" clause)
(agency, usage) => new {Agency = agency, Usage = usage }) // selection
.Where(x => x.Agency.OfficeId == id); // where statement

Write query in Entity Framework

I have a query which I ran successfully in SQL Server Management Studio, which returns the table values shown in the screenshot
The query I used is:
SELECT tcoid, COUNT(*) ownleasetank
FROM TankProfile
WHERE ownleasetank = 3
GROUP BY tcoid
Now I'm using Entity Framework to make things easier in my sample project.
I used this method to return the table values as array object:
public async Task<Object> GetLeaseInformationPrincipal()
{
ISOTMSEntities context = new ISOTMSEntities();
var testleaseinfo = from d in context.TankProfiles
join f in context.TankOperators
on d.tcoid equals f.tcoId
where (d.ownleasetank == 3)
select new { f.tcoName, d.ownleasetank } into x
group x by new { x.tcoName } into g
select new
{
tconame = g.Key.tcoName,
ownleasetank = g.Select(x => x.ownleasetank).Count()
};
return testleaseinfo.ToList();
}
but it is not working properly. I also tried other ways, when I use where and groupby method in Entity Framework it doesn't working properly for me.
Does anybody know the solution for this?
It's very simple with LINQ methods:
context.TankProfiles
.Where(t => t.ownleasetank = 3)
.GroupBy(t => t.tcoid)
.Select(g => new {g.Key, g.Count()})
.ToArray();
I have no idea why in your C# version of the query you have such opeartions such join, while your SQL query is very simple. You have to rethink that :)
var c = from t in context.TankProfile
where t.ownleasetank == 3
group t by t.tcoid into g
select new { tcoid=g.Key, ownleasetank=g.Select(x => x.ownleasetank).Count() };
return c.ToList();

How to create group clause in Entity Framework Core

I am trying to query 2 tables, Club and LinkClubUser. I want to retrieve the last club that a User is assigned from the last Date in the LinkclubUser.
I have the right SQL query:
select top 1
max(A.DataInscricao),
A.Nome, A.NomeNaCamisola, A.NumNaCamisola, A.Posicao, A.Situacao
from
Clube as A
inner join
LinkClubeUser as B on a.Id = b.IdClube
where
b.IdUser ='9faea9f3-28d7-4e34-8572-3102726d3c75'
group by
A.Nome, A.NomeNaCamisola, A.NumNaCamisola, A.Posicao, A.Situacao
I got the right row.
I try to convert this query to Entity Framework Core like this, but I get back more than 1 row:
var query = _dbContext
.LinkClubeUser
.Join(_dbContext.Clube,
lnk => lnk.IdClube,
clube => clube.Id,
(Lnk, clube) => new { Lnk, clube })
.Where(t => t.Lnk.IdUser == "9faea9f3-28d7-4e34-8572-3102726d3c75")
.GroupBy(t => new
{
t.clube.Id,
t.clube.Nome,
t.clube.NomeNaCamisola,
t.clube.NumNaCamisola,
t.clube.Posicao,
t.clube.Situacao,
t.clube.DataInscricao
}, t => t.clube)
.Select(g => new
{
Nome = g.Key.Nome,
NomeNaCamisola = g.Key.NomeNaCamisola,
NumNaCamisola = g.Key.NumNaCamisola,
Posicao = g.Key.Posicao,
Situacao = g.Key.Situacao,
DataInscricao = (DateTime)g.Max(p => p.DataInscricao)
}).Take(1);
but this code is converted by Entity Framework Core like this
SELECT
[lnk].[Id], [lnk].[Date], [lnk].[IdClub],
[lnk].[IdQuestionario], [lnk].[IdUser], [clube].[Id],
[clube].[ClubActual], [clube].[Date], [clube].[Nome],
[clube].[NomeNaCamisola], [clube].[NumNaCamisola], [clube].[Posicao],
[clube].[Situacao]
FROM
[LinkClubeUser] AS [lnk]
INNER JOIN
[Clube] AS [clube] ON [lnk].[IdClube] = [clube].[Id]
WHERE
[lnk].[IdUser] = N'9faea9f3-28d7-4e34-8572-3102726d3c75'
ORDER BY
[clube].[Id], [clube].[Nome], [clube].[NomeNaCamisola],
[clube].[NumNaCamisola], [clube].[Posicao], [clube].[Situacao],
[clube].[DataInscricao]
I don't see the group by clause.
What's wrong in my Entity Framework Core query?
I donĀ“t have the group clause.
I think you added all the clube table fields to your group clause so your group clause lost its nature and did not compile to SQL, while you added some of them in your first SQL query.
Edit
var query = (from user in _dbContext.LinkClubeUser
Join club in _dbContext.Clube on user.IdClub equals club.Id into cu
let clubUser = cu.DefaultIfEmpty() // outer join if you need it
Where clubUser.IdUser == "9faea9f3-28d7-4e34-8572-3102726d3c75")
Select new
{
Nome = user.Nome,
NomeNaCamisola = user.NomeNaCamisola,
NumNaCamisola = user.NumNaCamisola,
Posicao = user.Posicao,
Situacao = user.Situacao,
DataInscricao = (DateTime)clubUser.Max(p => p.DataInscricao)
}).Take(1);
Hope it helps.

Linq to Entities Left outer join grouped into a collection

from component in Materials.OfType<Container>().Where(m => m.Active)
join segmentFinanceRating in segmentFinanceRatingView on component.Id equals segmentFinanceRating.MaterialId into segmentFinanceRatingGroup
from segmentFinanceRatingWithDefault in segmentFinanceRatingGroup.DefaultIfEmpty()
select new
{
id = component.Id,
name = component.Name,
subType = component.SubType,
size = component.Size,
MaterialIds = component.Materials.Select(x => x.Id),
BrandNames = component.Brands.Select(x => x.Name),
SegmentRatings = segmentFinanceRatingWithDefault
}
I have the above LINQ to Entities query that has a LEFT JOIN to get rating values for 1 or more segments for a given component.
The segmentFinanceRating entity has the properties, { MaterialId, SegmentId, Rating, LowRated }
At the moment the results are not grouped to the relevant component, i.e. the SegmentRatings property is not a single collection of segmentFinanceRating objects, instead I have multiple data rows with 1 segmentFinanceRating object in each.
I have seen some examples of using group x by y into z but I couldn't get it working, possibly due to some of the collections on the component that I need too, I'm not sure.
Any help would be appreciated on how to do this, thanks.
GroupBy in List doesn't work for you?
var list = (from component in Materials.OfType<Container>().Where(m => m.Active)
join segmentFinanceRating in segmentFinanceRatingView on component.Id equals segmentFinanceRating.MaterialId into segmentFinanceRatingGroup
from segmentFinanceRatingWithDefault in segmentFinanceRatingGroup.DefaultIfEmpty()
select new
{
id = component.Id,
name = component.Name,
subType = component.SubType,
size = component.Size,
MaterialIds = component.Materials.Select(x => x.Id),
BrandNames = component.Brands.Select(x => x.Name),
SegmentRatings = segmentFinanceRatingWithDefault
}).ToList().GroupBy(s=> s.SegmentRatings);
In this case it's much easier to do the join in the anonymous type:
from component in Materials.OfType<Container>().Where(m => m.Active)
select new
{
id = component.Id,
name = component.Name,
subType = component.SubType,
size = component.Size,
MaterialIds = component.Materials.Select(x => x.Id),
BrandNames = component.Brands.Select(x => x.Name),
SegmentRatings = (from segmentFinanceRating in segmentFinanceRatingView
where segmentFinanceRating.MaterialId == component.Id
select segmentFinanceRating)
}
You will have an empty collection of SegmentRatings when there are none for a specific component, giving the same effect as outer join.

Entity Framework select distinct name

How can I do this SQL query with Entity Framework?
SELECT DISTINCT NAME FROM TestAddresses
Using lambda expression..
var result = EFContext.TestAddresses.Select(m => m.Name).Distinct();
Another variation using where,
var result = EFContext.TestAddresses
.Where(a => a.age > 10)//if you have any condition
.Select(m => m.name).Distinct();
Another variation using sql like syntax
var result = (from recordset
in EFContext.TestAddresses
.where(a => a.city = 'NY')//if you have any condition
.select new
{
recordset.name
}).Distinct();
Try this:
var results = (from ta in context.TestAddresses
select ta.Name).Distinct();
This will give you an IEnumerable<string> - you can call .ToList() on it to get a List<string>.
The way that #alliswell showed is completely valid, and there's another way! :)
var result = EFContext.TestAddresses
.GroupBy(ta => ta.Name)
.Select(ta => ta.Key);
I hope it'll be useful to someone.
DBContext.TestAddresses.Select(m => m.NAME).Distinct();
if you have multiple column do like this:
DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();
In this example no duplicate CategoryId and no CategoryName i hope this will help you
Entity-Framework Select Distinct Name:
Suppose if you are using Views in which you are using multiple tables and you want to apply distinct in that case first you have to store value in variable & then you can apply Distinct on that variable like this one....
public List<Item_Img_Sal_VIEW> GetItemDescription(int ItemNo)
{
var Result= db.Item_Img_Sal_VIEW.Where(p => p.ItemID == ItemNo).ToList();
return Result.Distinct().ToList();
}
Or you can try this Simple Example
Public Function GetUniqueLocation() As List(Of Integer)
Return db.LoginUsers.Select(Function(p) p.LocID).Distinct().ToList()
End Function
use Select().Distinct()
for example
DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();
In order to avoid ORDER BY items must appear in the select list if SELECT DISTINCT error, the best should be
var results = (
from ta in DBContext.TestAddresses
select ta.Name
)
.Distinct()
.OrderBy( x => 1);
Entity-Framework Select Distinct Name:
Suppose if you are want every first data of particular column of each group ;
var data = objDb.TableName.GroupBy(dt => dt.ColumnName).Select(dt => new { dt.Key }).ToList();
foreach (var item in data)
{
var data2= objDb.TableName.Where(dt=>dt.ColumnName==item.Key).Select(dt=>new {dt.SelectYourColumn}).Distinct().FirstOrDefault();
//Eg.
{
ListBox1.Items.Add(data2.ColumnName);
}
}

Categories

Resources