I have this LINQ query:
var agnts = (from a in db.agents select new { a.UserId, a.name }).Take(10);
How can I get randomly get 10 records from my agents table?
I have tried:
agnts = agnts.OrderBy(n => Guid.NewGuid());
but this doesn't seem to do anything.
I would appreciate anybody's help on this.
Thanks,
Louis
Then you do
agnts = agnts.OrderBy(n => Guid.NewGuid());
after
var agnts = (from a in db.agents select new { a.UserId, a.name }).Take(10);
agents are already taken. You need to specify OrderBy() before Take()
Related
How can we convert following query to LINQ
INSERT INTO License (PersonID, LicenseState, LicenseNumber, LicenseYear)
SELECT p.PersonID,
s.LicenseState,
s.LicenseNumber,
s.LicenseYear
FROM SourceData s
JOIN Person p
ON s.UserID = p.DomainAccountName
WHERE s.isActive = 1
var query = from s in db.SourceData
join p in db.Person on s.UserId equals p.DomainAccountName
where s.IsActive
select new License
{
PersonID = p.PersonID,
LicenseState = s.LicenseState,
LicenseNumber = s.LicenseNumber,
LicenseYear = s.LicenseYear
};
db.Licenses.AddRange(query);
That will actually give you one SQL query, and a bunch of individual SQL INSERTS. Alternately, you could use the Z.EntityFramework.Plus.EFCore nuget package, and use the code
var query = ... (same)...
db.Licenses.InsertFromQuery(query);
which should use the single SQL statement you posted.
UPDATE: I originally confused the retail/licensed Z.EntityFramework.Extensions.EFCore with the free/open-source Z.EntityFramework.Plus.EFCore package. Code above has been updated.
If you care about performance, you don't have to load anything to the client. It is how EF Core works right now, if you want to insert something - you have to feed ChangeTracker with new records.
I would suggest EF Core extension linq2db.EntityFrameworkCore which generates exactly the same query as in question but via LINQ. Note that I'm one of the creators.
Then you can do the following:
var query =
from s in db.SourceData
join p in db.Person on s.UserId equals p.DomainAccountName
where s.IsActive
select new License
{
PersonID = p.PersonID,
LicenseState = s.LicenseState,
LicenseNumber = s.LicenseNumber,
LicenseYear = s.LicenseYear
};
await query.InsertAsync(db.License.ToLinqToDBTable(), x => x);
I have two tables..
Student (StudentId,Name,FatherName)
Qualification (QualificationId,StudentId,DegreeName)
I have got data like this..
var myList = (from c in entities.Students
join q in entities.Qualifications on c.StudentId equals q.StudentId
select new {c.Name,c.FatherName,q.DegreeName}).ToList();
Now i want to filter myList more.. How can i do it, like..
var filteredList = myList.Select(c=> new Student
{
Name=c.Name,
FatherName=c.FatherName
//Degree=C.Degree
}).ToList();
The above Linq Query is not working if i want to get DegreeName also, My Question is how to further Filter myList.
Thanks.
var filteredList = myList.Where(i => i.FatherName == "Shahid").ToList();
Keep in mind since you called ToList() on the original query you are now filtering in memory. If you want to filter in the database then remove the ToList() on the first query and do it like this:
var myList = from c in entities.Students
join q in entities.Qualifications on c.StudentId equals q.StudentId
select new {
c.Name,
c.FatherName,
q.DegreeName
};
var filteredInDatabase = myList.Where(i => i.FatherName == "Shahid").ToList();
I have two lists containing data.
List<changeLogUsers> users;
UserID
List<changeLogQualifications> userQualifications;
UserID
QualificationID
I want to select only those userQualifications for which UserID is available in users list.
Can anyone help?
var result = userQualifications.Where(u => users.Any(x => x.UserID == u.UserID));
Try this
List<changeLogQualifications> userQualifications.Select(p=>p.UserID!=null);
Or alternatively:
var results = from uq in userQualifications
join u in users on uq.UserID equals u.UserID
select uq;
I'm having a bit trouble with a query in Linq to Entities which I hope someone can shed a light on :-) What I'm trying to do is to create a query that joins three tables.
So far it works, but since the last table I'm trying to join is empty, the result of the query doesn't contain any records. When I remove the last join, it gives me the right results.
My query looks like this:
var query = from p in db.QuizParticipants
join points in db.ParticipantPoints on p.id
equals points.participantId into participantsGroup
from po in participantsGroup
join winners in db.Winners on p.id
equals winners.participantId into winnersGroup
from w in winnersGroup
where p.hasAttended == 1 && p.weeknumber == weeknumber
select new
{
ParticipantId = p.id,
HasAttended = p.hasAttended,
Weeknumber = p.weeknumber,
UmbracoMemberId = p.umbMemberId,
Points = po.points,
HasWonFirstPrize = w.hasWonFirstPrize,
HasWonVoucher = w.hasWonVoucher
};
What I would like is to get some records even if the Winners table is empty or there is no match in it.
Any help/hint on this is greatly appreciated! :-)
Thanks a lot in advance.
/ Bo
If you set these up as related entities instead of doing joins, I think it will be easier to do what you're trying to do.
var query = from p in db.QuizParticipants
where p.hasAttended == 1 && p.weeknumber == weeknumber
select new
{
ParticipantId = p.id,
HasAttended = p.hasAttended,
Weeknumber = p.weeknumber,
UmbracoMemberId = p.umbMemberId,
Points = p.ParticipantPoints.Sum(pts => pts.points),
HasWonFirstPrize = p.Winners.Any(w => w.hasWonFirstPrize),
HasWonVoucher = p.Winners.Any(w => w.hasWonVoucher)
};
This is assuming hasWonFirstPrize and hasWonVoucher are boolean fields, but you can use any aggregate function to get the results you need, such as p.Winners.Any(w => w.hasWonFirstPrize == 1)
I don't use query syntax a lot but I believe you need to change from w in winnersGroup to from w in winnersGroup.DefaultIfEmpty()
Hello everyone,
I tried and tried to make this query in vb.net, but I can not.
I do not understand if I have to use two groups, and if so, how do I use them.
This is a query that is in the project - tutorial Tailspin SpyWorks
and should serve to show the 5 most popular products.
I do not understand really how to do.
var query = (from ProductOrders in db.OrderDetails
join SelectedProducts in db.Products on ProductOrders.ProductID
equals SelectedProducts.ProductID
group ProductOrders by new
{
ProductId = SelectedProducts.ProductID,
ModelName = SelectedProducts.ModelName
} into grp
select new
{
ModelName = grp.Key.ModelName,
ProductId = grp.Key.ProductId,
Quantity = grp.Sum(o => o.Quantity)
} into orderdgrp
where orderdgrp.Quantity > 0
orderby orderdgrp.Quantity descending
select orderdgrp).Take(5);
I tried to do the translation but I can not find documentation that helps me understand how do I manage two groups.
Dim query = (From ProductOrders in db.OrderDetails
Join SelectedProducts in db.Products On
ProductOrders.ProductID Equals SelectedProducts.ProductID
Group ProductOrders By New With
{
.ProductId = SelectedProducts.ProductID,
.ModelName = SelectedProducts.ModelName
} into grp
In fact from now on I can not go on
If someone can please help me out
Thanks a lot
Fabrizio
Im not an expert of VB language, but the following code is syntactically correct:
Dim query = (From ProductOrders In Products
Join SelectedProducts In SelProducts On ProductOrders.ProductId Equals SelectedProducts.ProductId
Group ProductOrders By Key = New With {
.ProductId = SelectedProducts.ProductId,
.ModelName = SelectedProducts.ModelName
} Into grp = Group
Select orderdgrp = New With
{
.ModelName = Key.ModelName,
.ProductId = Key.ProductId,
.Quantity = grp.Sum(Function(o) o.Quantity)
}
Where orderdgrp.Quantity > 0
Order By orderdgrp.Quantity Descending
Select orderdgrp).Take(5)
Verify that the query is also semantically correct.