Entity Framework - Selecting specific columns - asp.net-mvc-4

I have a successful query that links two tables with a where and orderby clause, but I wanted to add to just select specific columns instead of getting everything back.
PART 1
When I attempt this I get syntax errors on the orderby line, if I remove the orderby line the syntax errors move to the where line.
Error 3 Cannot implicitly convert type 'System.Linq.IOrderedQueryable' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)
IQueryable<VendorProfile> query = _db.VendorProfiles
.Include("VendorCategories")
.Include("VendorsSelected")
.Select(s => new { s.ProfileID, s.Name, s.CompanyName, s.City, s.State, s.DateCreated, s.VendorsSelected, s.VendorCategories })
.Where(x => x.VendorsSelected.Select(s => s.UserName).Contains(HttpContext.Current.User.Identity.Name))
.OrderBy(x => x.DateCreated);
if (criteria.name != string.Empty)
query = query.Where(v => v.Name.Contains(criteria.name));
if (criteria.company != string.Empty)
query = query.Where(v => v.CompanyName.Contains(criteria.company));
if (criteria.startDate != null && criteria.endDate != null)
query = query.Where(v => v.DateCreated > criteria.startDate && v.DateCreated < criteria.endDate);
if (criteria.categories != null && !criteria.categoryMatchAll)
query = query.Where(v => criteria.categories.AsQueryable().Any(cat => v.VendorCategories.Select(vendCat => vendCat.CategoryID).Contains(cat)));
if (criteria.categories != null && criteria.categoryMatchAll)
query = query.Where(v => criteria.categories.AsQueryable().All(cat => v.VendorCategories.Select(vendCat => vendCat.CategoryID).Contains(cat)));
if (criteria.minorityType != null)
query = query.Where(v => v.MinotiryOwned == criteria.minorityType);
if (criteria.diversityClass != null)
query = query.Where(v => v.DiversityClassification == criteria.diversityClass);
return query.ToList();
PART 2
I also wanted to know if I could extract the selected columns into a view model class, so I tired this and I get same results as above on the orderby line
Error 4 Cannot implicitly convert type 'System.Linq.IOrderedQueryable' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)

ANSWER
I think you helped me stumble upon the fact that the types don't match. Making the IQueryable type and the select new type and the return type the SAME makes the syntax happy. Using var does not like.
public IEnumerable<BrowseVendorModel> SearchVendors(CustomSearchModel criteria)
{
IQueryable<BrowseVendorModel> query = _db.VendorProfiles
.Include("VendorCategories")
.Include("VendorsSelected")
.Select(s => new BrowseVendorModel
{
ProfileID = s.ProfileID,
Name = s.Name,
CompanyName = s.CompanyName,
City = s.City,
State = s.State,
DateCreated = s.DateCreated,
VendorsSelected = s.VendorsSelected,
VendorCategories = s.VendorCategories
})
.Where(x => x.VendorsSelected.Select(s => s.UserName).Contains(HttpContext.Current.User.Identity.Name))
.OrderBy(x => x.DateCreated);
if (criteria.name != string.Empty)
query = query.Where(v => v.Name.Contains(criteria.name));
if (criteria.company != string.Empty)
query = query.Where(v => v.CompanyName.Contains(criteria.company));
if (criteria.startDate != null && criteria.endDate != null)
query = query.Where(v => v.DateCreated > criteria.startDate && v.DateCreated < criteria.endDate);
if (criteria.categories != null && !criteria.categoryMatchAll)
query = query.Where(v => criteria.categories.AsQueryable().Any(cat => v.VendorCategories.Select(vendCat => vendCat.CategoryID).Contains(cat)));
if (criteria.categories != null && criteria.categoryMatchAll)
query = query.Where(v => criteria.categories.AsQueryable().All(cat => v.VendorCategories.Select(vendCat => vendCat.CategoryID).Contains(cat)));
if (criteria.minorityType != null)
query = query.Where(v => v.MinotiryOwned == criteria.minorityType);
if (criteria.diversityClass != null)
query = query.Where(v => v.DiversityClassification == criteria.diversityClass);
return query;
}

The first example requires var because you are changing the shape of the query by projecting into anonymous type. The second example can either use var or IQueryable<VendorProfileViewModel> because you are changing the shape of the query by projecting into VendorProfileViewModel.

Related

Getting error 'Unable to translate a collection subquery in a projection' when using union and select together in EF Core 7

I wrote a code that EF Core creates an expression for that looks like this:
DbSet<Reception>()
.Include(x => x.Employee)
.Include(x => x.ReceptionSignatures)
.Where(x => x.Employee.FirstName.Contains("mo"))
.Union(DbSet<Reception>()
.Include(x => x.Employee)
.Include(x => x.ReceptionSignatures)
.Where(x => x.Employee.PersonelId.Contains("mo")))
.Union(DbSet<Reception>()
.Include(x => x.Employee)
.Include(x => x.ReceptionSignatures)
.Where(x => x.Employee.LastName.Contains("mo")))
.Union(DbSet<Reception>()
.Include(x => x.Employee)
.Include(x => x.ReceptionSignatures)
.Where(x => x.Employee.NationId.Contains("mo")))
.OrderBy(x => x.Employee.FirstName.CompareTo("mo") == 0 ? 0 : 1)
.Select(r => new ReceptionAllDTO{
ReceptionId = r.Id,
NationId = r.Employee.NationId,
PersonelId = r.Employee.PersonelId,
FirstName = r.Employee.FirstName,
LastName = r.Employee.LastName,
Birthday = r.Employee.Birthday,
RecepDate = r.RecepDate,
Height = r.Height,
Weight = r.Weight,
ReceptionSignatures = r.ReceptionSignatures,
}
)
In Reception entity, I have a relation to Signature like this:
public virtual ICollection<Signature> ReceptionSignatures { get; set; }
but when EF Core wants to create a query for SQL, it throws this exception:
Unable to translate a collection subquery in a projection since either parent or the subquery doesn't project necessary information required to uniquely identify it and correctly generate results on the client side. This can happen when trying to correlate on keyless entity type. This can also happen for some cases of projection before 'Distinct' or some shapes of grouping key in case of 'GroupBy'. These should either contain all key properties of the entity that the operation is applied on, or only contain simple property access expressions.
It seems like you are querying for more data which is really not efficient. Its better to project your required columns using the Select() and then write a Union.
When writing the Union the number of columns Selected must be same as shown below from a code base i wrote 2 weeks ago and which works.
var billPaymentVoucherQuery = _context.Set<BillPaymentVoucher>().AsQueryable();
var billsQuery = _context.Set<Bill>().AsQueryable();
var anon_billsQuery = billsQuery.Where(w => w.InvoiceDate.Date <= filter.AsAtDate.Date)
.Where(w => w.OperationalStatus == OperationalBillStatus.Approved &&
(
w.FinancialStatus == FinancialBillStatus.Pending ||
w.FinancialStatus == FinancialBillStatus.OnHold ||
w.FinancialStatus == FinancialBillStatus.PartiallyApproved ||
w.FinancialStatus == FinancialBillStatus.Approved
))
.Select(s => new
{
VendorName = s.VendorInvoice.Vendor!.Name,
Type = "Bill",
Date = s.InvoiceDate,
Number = Convert.ToString(s.InvoiceNumber),
Amount = s.LineItemTotal + s.VATAmount
}).AsQueryable();
var anon_billPaymentVoucherQuery = billPaymentVoucherQuery
.Where(w => (
w.UpdatedOn.HasValue &&
w.UpdatedOn.Value.Date <= filter.AsAtDate.Date
)
||
(
w.UpdatedOn.HasValue == false &&
w.CreatedOn.Date <= filter.AsAtDate.Date
))
.Where(w => w.BillPaymentVoucherStatus == BillPaymentVoucherStatus.Paid)
.Select(s => new
{
VendorName = s.PaymentApprovedBill.Bill.VendorInvoice.Vendor!.Name,
Type = "Payment",
Date = s.UpdatedOn ?? s.CreatedOn,
Number = Convert.ToString(s.PaymentApprovedBill.Bill.InvoiceNumber + " | " +
s.PaymentVoucherNumber),
Amount = -s.PayAmount
}).AsQueryable();
var unionedQuery = anon_billsQuery.Union(anon_billPaymentVoucherQuery)
.Where(w => string.IsNullOrWhiteSpace(filter.Type) || w.Type == filter.Type);
int pageSize = 2;
bool hasMoreRecords = true;
var transactionData = await unionedQuery.OrderBy(w => w.VendorName)
.ThenBy(w => w.Date)
.Skip((paginator.PageNumber - 1) * pageSize)
.Take(pageSize)
.ToListAsync(token);

The ExceptResultOperator result operator is not current supported

I want to exclude one resultset from another and I am using Except for that but it is giving error that "The ExceptResultOperator result operator is not current supported". I can not use all the conditions in where clause of a single query as it will give me unexcepted result.
//Sample code what I have tried
var result1 = Session.Query<Table>()
.Where(x => x.ColumnName != null && !x.active)
.Select(x => x)
var result2 = Session.Query<Table>()
.Where(x => x.Active)
.Except(result1)
.Select(x => x)
You can use Contains instead of Except:
var result1 = Session.Query<Table>()
.Where(x => x.ColumnName != null && !x.active)
.Select(x => x)
var result2 = Session.Query<Table>()
.Where(x => x.Active && !result1.Contains(x))
.Select(x => x)

How to perform following query in LINQ?

I have a SQL query need to do in LINQ. Can anyone helps in converting?
SELECT *
FROM profile
WHERE ProfileId <> 1221 AND IsActive = 1 AND
ProfileId NOT IN (SELECT ReportingPerson
FROM ReportingPersons
WHERE Employee = 1221)
var reportingPerson = context.ReportingPersons.Where(x =>
x.Employee == 1221)
.Select(c => c.ReportingPerson
).ToList();
var result = context.Profiles
.Where(x =>
x.ProfileId != 1221 &&
x.IsActive &&
!reportingPerson.Contains(x.ProfileId)
.ToList();

How to Convert Sql to Linq with Distinct(id)

select count(distinct LicencePlate) from MT_Vehicle where IsDeleted=0 and CreatedBy = 1
var count = MT_Vehicle.Where(x => x.IsDeleted==0 && x.CreatedBy == 1)
.Select(x => x.LicencePlate)
.Distinct()
.Count();
You can write that as:
var count = db.MT_Vehicle
.Where( v => v.IsDeleted == 0 && v.CreatedBy == 1 )
.Select(v => v.LicencePlate)
.Distinct()
.Count();

fluent hibernate Transformers.AliasToBean is not working as expected

I have three tables. One is the master table: TableA. One table is referenced by TableA called ReferencedTable and lastly a lookup table referenced by ReferencedTable.
I have this query that returns the ten most recent objects as:
TableADTO TableAlias = null;
LookupTableDTO LookupTableAlias = null;
ReferencedDTO ReferencedAlias = null;
dtos = session.QueryOver(() => TableAlias)
.JoinAlias(() => TableAlias.Object, () =>ReferencedAlias)
.JoinAlias(() => ReferencedAlias.ObjectType, () => LookupTableAlias)
.Where(() => ReferencedAlias.PersonId == user.Id &&
(LookupTableAlias.Id != INVOICE_ID ||
LookupTableAlias.Id != FINANCIAL_ID) &&
TableAlias.Status == NEW_STATUS_FLAG &&
ReferencedAlias.ReceivedDate < DateTime.Now)
.Take(10)
.List()
.Select(dto=>
new AbreviatedDTO
{
Id = dto.Referenced.Id,
Field1 = dto.Field1,
Priority = dto.Referenced.Priority,
ReceivedDate = dto.Referenced.ReceivedDate,
Field1 = dto.Referenced.Field1,
Type = dto.Referenced.Lookup.TypeCode,
Status = dto.Status
}).ToList();
This works as expected. However, I thought the the transformation below would work too. It does bring 10 objects but the objects have all default values and are not populated (e.g. AbreviatedDTO.ReceivedDate = DateTime.Minimum). Am I doing something wrong with the QueryOver?
Any help would be appreciated.
Bill N
TableDTO TableAlias = null;
LookupTableDTO LookupTableAlias = null;
ReferencedDTO ReferencedAlias = null;
dtos = session.QueryOver(() => TableAlias)
.JoinAlias(() => TableAlias.Object, () =>ReferencedAlias)
.JoinAlias(() => ReferencedAlias.ObjectType, () => LookupTableAlias)
.Where(() => ReferencedAlias.PersonId == user.Id &&
(LookupTableAlias.Id != INVOICE_ID ||
LookupTableAlias.Id != FINANCIAL_ID) &&
TableAlias.Status == NEW_STATUS_FLAG &&
ReferencedAlias.ReceivedDate < DateTime.Now)
.SelectList(list => list
.Select(x => TableAlias.Field1)
.Select(x => ReferencedAlias.Id)
.Select(x => ReferencedAlias.Field1)
.Select(x => ReferencedAlias.ReceivedDate)
.Select(x => ReferencedAlias.Priority)
.Select(x => LookupTableAlias.TypeCode))
.TransformUsing(Transformers.AliasToBean<AbreviatedDTO>())
.Take(10)
.List<AbreviatedDTO>()
you'll need to define an alias for each selected field same as the propertyname in the resulting dto
AbreviatedDTO alias = null;
// in query
.SelectList(list => list
.Select(() => TableAlias.Field1).WithAlias(() => alias.Field1)