How to make this expression using the methods of exptension, but (!) not using anonymous types?
from p in posts
join u in context.oxite_Users on p.CreatorUserID equals u.UserID
join pa in context.oxite_PostAreaRelationships on p.PostID equals pa.PostID
join a in context.oxite_Areas on pa.AreaID equals a.AreaID
let c = getCommentsQuery(p.PostID)
let t = getTagsQuery(p.PostID)
let tb = getTrackbacksQuery(p.PostID)
let f = getFilesQuery(p.PostID)
where p.State != (byte)EntityState.Removed
orderby p.PublishedDate descending
select new Post
{ area = a, comments = c } e.t.c.
The key here is to introduce a tuple that encapsulates the combined state of the join operations and other lets. I can't repro your environment just from that, but here's a limited example that should make it clear(ish);
using System.Linq;
static class Program
{
static void Main()
{
var users = new User[0]; // intentionally 0; only exists to prove compiles
var orders = new Order[0];
var query = users.Join(orders, user => user.UserId, order => order.OrderId, (user,order) => new UserOrderTuple(user,order))
.Where(tuple => tuple.State != 42).OrderByDescending(tuple => tuple.Order.OrderId)
.Select(tuple => new ResultTuple { Comment = tuple.Comment });
}
}
class ResultTuple
{
public string Comment { get; set; }
}
class UserOrderTuple
{
public UserOrderTuple(User user, Order order)
{
User = user;
Order = order;
Comment = "some magic that gets your comment and other let";
State = 124;
}
public string Comment { get; private set; }
public int State { get; private set; }
public User User { get; private set; }
public Order Order { get; private set; }
}
class User
{
public int UserId { get; set; }
}
class Order
{
public int UserId { get; set; }
public int OrderId { get; set; }
}
Related
I'm trying to build a lambda expression to get the grand total but I'm still struggling to achieve the desired result. I've managed to achieve the same using SQL and LINQ using joints but it would be great if someone could give me a hand to re-write the query using lambda and navigation properties (without joints).
SQL Query:
SELECT SUM(a.[Quantity] * (a.[Price] + b.[ExtraValue])) + SUM(d.SubMealTotal * a.[Quantity]) AS [Total]
FROM [dbo].[OrderedMeals] a
INNER JOIN [dbo].[OrderedMealPortions] b
ON a.Id = b.[OrderedMealId]
LEFT OUTER JOIN (SELECT OrderedMealId, Sum(Price) AS SubMealTotal FROM [dbo].[OrderedSubMeals]
GROUP BY OrderedMealId) AS d
ON a.Id = d.[OrderedMealId]
WHERE a.[Quantity] > 0
Then the LINQ - Please let me know if I'm missing something here or there is a better way:
(from orderedMeal in _context.OrderedMeals.Where(x => x.Quantity > 0)
join orderedMealPortion in _context.OrderedMealPortions
on orderedMeal.Id equals orderedMealPortion.OrderedMealId
join orderedSubMeal in _context.OrderedSubMeals
on orderedMeal.Id equals orderedSubMeal.OrderedMealId into gs
from subOrderedSubMeal in gs.DefaultIfEmpty()
group subOrderedSubMeal by new { subOrderedSubMeal.OrderedMealId, orderedMeal.Price, orderedMeal.Quantity, orderedMealPortion.ExtraValue } into g
select new
{
MealTotal = (g.Key.ExtraValue + g.Key.Price) * g.Key.Quantity + g.Sum(x => x.Price * g.Key.Quantity),
}).Sum(x => x.MealTotal); // Not sure how to get the sum using LINQ
Entities:
public class OrderedMeal
{
public int Id { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
public int OrderedMealPortionId { get; set; }
public OrderedMealPortion? OrderedMealPortion { get; set; }
public ICollection<OrderedSubMeal>? OrderedSubMeals { get; set; }
}
public class OrderedMealPortion
{
public int Id { get; set; }
public int OrderedMealId { get; set; }
public OrderedMeal? OrderedMeal { get; set; }
public decimal? ExtraValue { get; set; }
}
public class OrderedSubMeal
{
public int Id { get; set; }
public int OrderedMealId { get; set; }
public OrderedMeal? OrderedMeal { get; set; }
public decimal Price { get; set; }
}
I can't test with a database, but I think this implements the query logic and will produce the same result:
var ans = OrderedMeals
.Where(om => om.Quantity > 0 && om.OrderedMealPortion != null)
.Sum(om => om.Quantity * (om.Price +
om.OrderedMealPortion!.ExtraValue +
(om.OrderedSubMeals != null ? om.OrderedSubMeals.Sum(osm => osm.Price) : 0)) );
This is direct translation from the SQL:
var groupingQuery =
from sm in _context.OrderedSubMeals
group sm by new { sm.OrderedMealId } into g
select new
{
g.Key.OrderedMealId,
SubMealTotal = g.Sum(x => x.Price)
};
var query =
from om in _context.OrderedMeals
join g in groupingQuery on om.Id equals g.OrderedMealId into gj
from g in gj.DefaultIfEmpty()
where om.Quantity > 0
select new { om, om.OrderedMealPortion, g };
var result = query.Sum(x => x.om.Quantity * (x.om.Price + x.OrderedMealPortion.ExtraValue + x.g.SubMealTotal));
But I have feeling that query can be simplified without grouping.
I am working to convert the below SQL code to LINQ query for MVC. It got multiple nested joins and group by.
SELECT UnitTracts.Id,
UnitTracts.UnitId,
Leases.Id,
Leases.Lessor,
Leases.Lessee,
Leases.Alias,
Leases.LeaseDate,
Leases.GrossAcres,
IIf([Page] Is Null,[VolumeDocumentNumber],[VolumeDocumentNumber] + '/' + [Page]) AS [Vol/Pg],
Leases.Legal,
Interests.TractId,
Leases.NetAcres,
UnitTracts.AcInUnit
FROM (UnitTracts INNER JOIN (((WorkingInterestGroups INNER JOIN Interests ON WorkingInterestGroups.Id = Interests.WorkingInterestGroupId)
INNER JOIN Tracts ON Interests.TractId = Tracts.Id)
INNER JOIN Leases ON WorkingInterestGroups.LeaseId = Leases.Id)
ON UnitTracts.TractId = Tracts.Id)
LEFT JOIN AdditionalLeaseInfo ON Leases.Id = AdditionalLeaseInfo.LeaseId
where unitId = 21
GROUP BY UnitTracts.Id,
UnitTracts.UnitId,
Leases.Id,
Leases.Lessor,
Leases.Lessee,
Leases.Alias,
Leases.LeaseDate,
Leases.GrossAcres,
IIf([Page] Is Null,[VolumeDocumentNumber],[VolumeDocumentNumber] + '/' + [Page]),
Leases.Legal,
Interests.TractId,
Leases.NetAcres,
UnitTracts.AcInUnit
This the query I got but it returns less records. I tried to convert from SQL to LINQ but it did not work. I really stuck now.
var leases = (from l in db.Leases
where l.Active
join ali in db.AdditionalLeaseInfoes on l.Id equals ali.LeaseId
where ali.Active
join wig in db.WorkingInterestGroups on l.Id equals wig.LeaseId
where wig.Active
join interest in db.Interests on wig.Id equals interest.WorkingInterestGroupId
where interest.Active
join tr in db.Tracts on interest.TractId equals tr.Id
where tr.Active
join ut in db.UnitTracts on tr.Id equals ut.TractId
where ut.Active
group new { l, wig, interest, tr, ali, ut } by
new
{
Id = ut.Id,
UnitId = ut.UnitId,
LeaseId = l.Id,
Lessor = l.Lessor,
Lessee = l.Lessee,
Alias = l.Alias,
LeaseDate = l.LeaseDate,
GrossAcres = l.GrossAcres,
VolPg = l.Page == null ? l.VolumeDocumentNumber : l.VolumeDocumentNumber + "/" + l.Page,
Legal = l.Legal,
TractId = interest.TractId,
NetAcres = l.NetAcres,
AcInUnit = ut.AcInUnit
} into lease
select new LeasesViewModel
{
UnitId = lease.Key.UnitId,
TractId = lease.Key.TractId,
LeaseId = lease.Key.LeaseId,
LeaseAlias = lease.Key.Alias,
Pooling = lease.Where(x => x.l.Id == lease.Key.LeaseId).Select(x => x.l.NoPooling).FirstOrDefault() ? "No" :
lease.Where(x => x.l.Id == lease.Key.LeaseId).Select(x => x.l.Pooling).FirstOrDefault() ? "Yes" : "No Review",
Lessor = lease.Key.Lessor,
GrossAc = lease.Key.GrossAcres
}).Where(x => x.UnitId == unitId).OrderBy(x => x.TractId).ToList();
Thanks for help!!
Thanks for help!!
Thanks for help!!
Thanks for help!!
I modeled you query with classes to get syntax correct :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<WorkingInterestGroups> workingInterestGroups = new List<WorkingInterestGroups>();
List<UnitTracts> unitTracts = new List<UnitTracts>();
List<Tracts> tracts = new List<Tracts>();
List<Leases> leases = new List<Leases>();
List<AdditionalLeaseInfo> additionalLeaseInfos = new List<AdditionalLeaseInfo>();
List<Interests> interests = new List<Interests>();
var results = (from unitTract in unitTracts
join tract in tracts on unitTract.TractId equals tract.Id
join interest in interests on tract.Id equals interest.TractId
join workingInterestGroup in workingInterestGroups on interest.WorkingInterestGroupId equals workingInterestGroup.Id
join lease in leases on workingInterestGroup.LeaseId equals lease.Id
join additionalLeaseInfo in additionalLeaseInfos on lease.Id equals additionalLeaseInfo.LeaseId
where unitTract.UnitId == "21"
select new { unitTract = unitTract, tract = tract, interest = interest, workingInterestGroup = workingInterestGroup,
lease = lease, additionalLeaseInfo = additionalLeaseInfo}).ToList();
var groups = results.GroupBy(x => new
{
x.unitTract.Id,
x.unitTract.UnitId,
x.lease.Lessor,
x.lease.Lessee,
x.lease.Alias,
x.lease.LeaseDate,
x.lease.GrossAcres,
x.lease.Legal,
x.interest.TractId,
x.lease.NetAcres,
x.unitTract.AcInUnit
})
.ToList();
}
}
public class WorkingInterestGroups
{
public string Id { get; set; }
public string LeaseId { get; set; }
}
public class UnitTracts
{
public string TractId { get; set; }
public string Id { get; set; }
public string UnitId { get; set; }
public string AcInUnit { get;set;}
}
public class Tracts
{
public string Id { get; set; }
}
public class Leases
{
public string Id { get; set; }
public string Lessor { get; set; }
public string Lessee { get; set; }
public string Alias { get; set; }
public string LeaseDate { get; set; }
public string GrossAcres { get; set; }
public string Legal { get; set; }
public string NetAcres { get; set; }
}
public class AdditionalLeaseInfo
{
public string LeaseId { get; set;}
}
public class Interests
{
public string TractId { get; set; }
public string WorkingInterestGroupId { get; set; }
}
}
I donĀ“t know where is the mistake why it says that does not contain a defintion of ImporteSolicitado, interesesDemora and importeReintegro when they are colums of c and the last one of d
var importes = (from c in _context.ReintegroSolicitado
join d in _context.ReintegroRecibido on c.Expediente.ID equals d.Expediente.ID
group new {c,d} by new { c.Expediente.Codigo} into cd
select new { ImporteSolictadoFinal = cd.Sum(b => b.ImporteSolicitado + b.InteresesDemora), ImporteReintegroFinal = cd.Sum(e => e.ImporteReintegro) });
your group element contains two property c and d. So you need refer to
this property as
...
select new {
ImporteSolictadoFinal = cd.Sum(b => b.c.ImporteSolicitado + b.c.InteresesDemora),
ImporteReintegroFinal = cd.Sum(e => e.d.ImporteReintegro) }
...
This is very tough to get right with query posted. I did my best, but it is probably not exactly correct.
var importes = (from c in _context.reintegroSolicitado
join d in _context.reintegroRecibido on c.expediente.ID equals d.expediente.ID
select new { reintegroSolicitado = c, reintegroRecibido = c})
.GroupBy(x => new { c = x.reintegroSolicitado , d = x.reintegroRecibido})
.Select(cd => new { ImporteSolictadoFinal = cd.Sum(b => b.reintegroSolicitado.ImporteSolicitado + b.reintegroSolicitado.InteresesDemora), ImporteReintegroFinal = cd.Sum(e => e.reintegroRecibido.ImporteReintegro) });
}
}
public class Context
{
public List<ReintegroSolicitado> reintegroSolicitado { get; set; }
public List<ReintegroSolicitado> reintegroRecibido { get; set; }
public Expediente expediente { get; set; }
}
public class ReintegroSolicitado
{
public Expediente expediente { get; set; }
public int ImporteSolicitado { get; set; }
public int InteresesDemora { get; set; }
public int ImporteReintegro { get; set; }
}
public class Expediente
{
public int ID { get; set; }
public int Codigo { get; set; }
}
I have to next 2 entities in my project
public class Product
{
public Product()
{
this.ProductImages = new HashSet<ProductImage>();
this.ProductParams = new HashSet<ProductParam>();
}
public int ID { get; set; }
public int BrandID { get; set; }
public int CodeProductTypeID { get; set; }
public string SeriaNumber { get; set; }
public string ModelNumber { get; set; }
public decimal Price { get; set; }
public bool AvailableInStock { get; set; }
public virtual Brand Brand { get; set; }
public virtual CodeProductType CodeProductType { get; set; }
public virtual ICollection<ProductImage> ProductImages { get; set; }
public virtual ICollection<ProductParam> ProductParams { get; set; }
}
public class ProductParam
{
public int Id { get; set; }
public int ProductId { get; set; }
public int CodeProductParamId { get; set; }
public string Value { get; set; }
public virtual Product Product { get; set; }
public virtual CodeProductParam CodeProductParam { get; set; }
}
and I want to get list of Products which has list of specified parameters
var prodParamCritria = new List<ProductParam>()
{
new ProductParam(){CodeProductParamId =1, Value="Black" },
new ProductParam(){CodeProductParamId =2, Value="Steal"}
};
in sql I can do it by using EXISTS clause twise
SELECT *
FROM Products p
WHERE EXISTS (
SELECT *
FROM ProductParams pp
WHERE pp.ProductId = p.ID
AND (pp.CodeProductParamId = 1 AND pp.[Value] = N'Black')
)
AND EXISTS (
SELECT *
FROM ProductParams pp
WHERE pp.ProductId = p.ID
AND pp.CodeProductParamId = 2
AND pp.[Value] = N'Steal'
)
How can i get same result by EF methods or linq
Try this:
var products= db.Products.Where(p=>p.ProductParams.Any(pp=>pp.CodeProductParamId == 1 && pp.Value == "Black") &&
p.ProductParams.Any(pp=>pp.CodeProductParamId == 2 && pp.Value == "Steal"));
Update
The problem in work with that list of ProductParam to use it as a filter is that EF doesn't know how to translate a PodructParam object to SQL, that's way if you execute a query like this:
var products2 = db.Products.Where(p => prodParamCritria.All(pp => p.ProductParams.Any(e => pp.CodeProductParamId == e.CodeProductParamId && pp.Value == e.Value)));
You will get an NotSupportedException as you comment in the answer of #BostjanKodre.
I have a solution for you but probably you will not like it. To resolve that issue you could call the ToList method before call the Where. This way you will bring all products to memory and you would work with Linq to Object instead Linq to Entities, but this is extremely inefficient because you are filtering in memory and not in DB.
var products3 = db.Products.ToList().Where(p => prodParamCritria.All(pp => p.ProductParams.Any(e => pp.CodeProductParamId == e.CodeProductParamId && pp.Value == e.Value)));
If you want filter by one criteria then this could be more simple and you are going to be able filtering using a list of a particular primitive type. If you, for example, want to filter the products only by CodeProductParamId, then you could do this:
var ids = new List<int> {1, 2};
var products = db.Products.Where(p => ids.All(i=>p.ProductParams.Any(pp=>pp.CodeProductParamId==i))).ToList();
This is because you are working with a primitive type and not with a custom object.
I suppose something like that should work
db.Product.Where(x => x.ProductParams.FirstOrDefault(y => y.CodeProductParamId == 1) != null && x.ProductParams.FirstOrDefault(y => y.CodeProductParamId == 2) != null).ToList();
or better
db.Product.Where(x => x.ProductParams.Any(y => y.CodeProductParamId == 1) && x.ProductParams.Any(y => y.CodeProductParamId == 2)).ToList();
Ok, if you need to make query on parameters in list prodParamCriteria it will look like this:
db.Product.Where(x => prodParamCritria.All(c=> x.ProductParams.Any(p=>p.CodeProductParamId == c.CodeProductParamId && p.Value== c.Value))).ToList();
I forgot that complex types cannot be used in query database, so i propose you to convert your prodParamCriteria to dictionary and use it in query
Dictionary<int, string> dctParams = prodParamCritria.ToDictionary(x => x.CodeProductParamId , y=>y.Value);
db.Product.Where(x => dctParams.All(c => x.ProductParams.Any(p=> p.CodeProductParamId == c.Key && p.Value== c.Value))).ToList();
another variation:
IEnumerable<Int32> lis = prodParamCritria.Select(x => x.CodeProductParamId).ToList();
var q = Products.Select(
x => new {
p = x,
cs = x.ProductParams.Where(y => lis.Contains(y.Id))
}
).Where(y => y.cs.Count() == lis.Count()).
ToList();
with a named class like (or maybe without, but not in linqpad)
public class daoClass {
public Product p {get; set;}
public Int32 cs {get; set;}
}
IEnumerable<Int32> lis = prodParamCritria.Select(x => x.CodeProductParamId).ToList();
var q = Products.Select(
x => new daoClass {
p = x,
cs = x.ProductParams.Where(y => lis.Contains(y.Id))
}
).Where(y => y.cs.Count() == lis.Count()).
SelectMany(y => y.p).
ToList();
I hope it's more clear what I want to do from the code than the title. Basically I am grouping by 2 fields and want to reduce the results into a collection all the ProductKey's constructed in the Map phase.
public class BlockResult
{
public Client.Names ClientName;
public string Block;
public IEnumerable<ProductKey> ProductKeys;
}
public Block()
{
Map = products =>
from product in products
where product.Details.Block != null
select new
{
product.ClientName,
product.Details.Block,
ProductKeys = new List<ProductKey>(new ProductKey[]{
new ProductKey{
Id = product.Id,
Url = product.Url
}
})
};
Reduce = results =>
from result in results
group result by new {result.ClientName, result.Block} into g
select new BlockResult
{
ClientName = g.Key.ClientName,
Block = g.Key.Block,
ProductKeys = g.SelectMany(x=> x.ProductKeys)
};
}
I get some weird System.InvalidOperationException and a source code dump where basically it is trying to initialize the list with an int (?).
If I try replacing the ProductKey with just IEnumerable ProductIds (and make appropriate changes in the code). Then the code runs but I don't get any results in the reduce.
You probably don't want to do this. Are you really going to need to query in this manner? If you know the context, then you should probably just do this:
var q = session.Query<Product>()
.Where(x => x.ClientName == "Joe" && x.Details.Block == "A");
But, to answer your original question, the following index will work:
public class Products_GroupedByClientNameAndBlock : AbstractIndexCreationTask<Product, Products_GroupedByClientNameAndBlock.Result>
{
public class Result
{
public string ClientName { get; set; }
public string Block { get; set; }
public IList<ProductKey> ProductKeys { get; set; }
}
public class ProductKey
{
public string Id { get; set; }
public string Url { get; set; }
}
public Products_GroupedByClientNameAndBlock()
{
Map = products =>
from product in products
where product.Details.Block != null
select new {
product.ClientName,
product.Details.Block,
ProductKeys = new[] { new { product.Id, product.Url } }
};
Reduce = results =>
from result in results
group result by new { result.ClientName, result.Block }
into g
select new {
g.Key.ClientName,
g.Key.Block,
ProductKeys = g.SelectMany(x => x.ProductKeys)
};
}
}
When replicating I get the same InvalidOperationException, stating that it doesn't understand the index definition (stack trace omitted for brevity).
Url: "/indexes/Keys/ByNameAndBlock"
System.InvalidOperationException: Could not understand query:
I'm still not entirely sure what you're attempting here, so this may not be quite what you're after, but I managed to get the following working. In short, Map/Reduce deals in anonymous objects, so strongly typing to your custom types makes no sense to Raven.
public class Keys_ByNameAndBlock : AbstractIndexCreationTask<Product, BlockResult>
{
public Keys_ByNameAndBlock()
{
Map = products =>
from product in products
where product.Block != null
select new
{
product.Name,
product.Block,
ProductIds = product.ProductKeys.Select(x => x.Id)
};
Reduce = results =>
from result in results
group result by new {result.Name, result.Block}
into g
select new
{
g.Key.Name,
g.Key.Block,
ProductIds = g.SelectMany(x => x.ProductIds)
};
}
}
public class Product
{
public Product()
{
ProductKeys = new List<ProductKey>();
}
public int ProductId { get; set; }
public string Url { get; set; }
public string Name { get; set; }
public string Block { get; set; }
public IEnumerable<ProductKey> ProductKeys { get; set; }
}
public class ProductKey
{
public int Id { get; set; }
public string Url { get; set; }
}
public class BlockResult
{
public string Name { get; set; }
public string Block { get; set; }
public int[] ProductIds { get; set; }
}