getting issues in soql. The left operand field in the where expression for outer query should be an id field, cannot use: 'RecordId - apex

public with sharing class RecordTypeController {
#AuraEnabled(cacheable=true)
public static List<RecordTypeInfoWrapper> getRecordTypes(String objectName) {
List<RecordTypeInfoWrapper> recordTypes = new List<RecordTypeInfoWrapper>();
Map<Id, RecordTypeInfoWrapper> recordTypeMap = new Map<Id, RecordTypeInfoWrapper>();
List<UserRecordAccess> userRecordAccesses = [SELECT RecordId FROM UserRecordAccess WHERE UserId = :UserInfo.getUserId() AND HasReadAccess = true AND RecordId IN (SELECT Id FROM RecordType WHERE SobjectType = :objectName AND IsActive = true)];
for (UserRecordAccess userRecordAccess : userRecordAccesses) {
RecordType recordType = [SELECT Id, Name FROM RecordType WHERE Id = :userRecordAccess.RecordId];
recordTypeMap.put(recordType.Id, new RecordTypeInfoWrapper(recordType));
}
for (RecordTypeInfoWrapper recordType : recordTypeMap.values()) {
recordTypes.add(recordType);
}
return recordTypes;
}
public class RecordTypeInfoWrapper {
#AuraEnabled
public String Id { get; set; }
#AuraEnabled
public String Name { get; set; }
public RecordTypeInfoWrapper(RecordType recordType) {
Id = recordType.Id;
Name = recordType.Name;
}
}
}
tried replcing id with recordid but then got The selected field 'Id' in the subquery and the left operand field in the where expression in the outer query 'id' should point to the same object type (7:53) error

Related

list in entity framework and webapi

I am trying to return employee with three column in .net webapi with entity framework but return gives error saying cannot convert type pf anonymous to emp ..what I am missing
public List<EMPLOYEE_DTLS> GetLoginInfo(string UserId)
{
var result = (from emp in db.EMPLOYEE_DTLS
where emp.UserId == UserId
select new
{
emp.FullName,
emp.Role,
emp.Designation
}).ToList();
return result;
}
You should use a DTO to return the list.
public class EmployeeDTO
{
public string FullName {get; set;}
public string Role {get; set;}
public string Designation {get; set;}
}
public List<EmployeeDTO> GetLoginInfo(string UserId)
{
var result = (from emp in db.EMPLOYEE_DTLS
where emp.UserId == UserId
select new EmployeeDTO
{
FullName = emp.FullName,
Role = emp.Role,
Designation = emp.Designation
}).ToList();
return result;
}
Your method returns List<EMPLOYEE_DTLS>, but you are trying to return List of anonymous type.
Assuming you EMPLOYEE_DTLS class has properties FullName, Role and Designation change the type you are selecting:
public List<EMPLOYEE_DTLS> GetLoginInfo(string UserId)
{
var result = (from emp in db.EMPLOYEE_DTLS
where emp.UserId == UserId
select new EMPLOYEE_DTLS
{
FullName = emp.FullName,
Role = emp.Role,
Designation = emp.Designation
}).ToList();
return result;
}

Entity Framework Core Select Outer Join

is there an easy way to include a nullable navigation inside a select expression for EF Core?
My model looks like this
public class RootVO
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(200)]
public string Description { get; set; }
public int? RelationId { get; set; }
[ForeignKey(nameof(RelationId))]
public RelationVO Relation { get; set; }
}
public class RelationVO
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(200)]
public string Property1 { get; set; }
[Required]
[StringLength(200)]
public string Property2 { get; set; }
public ICollection<RootVO> RootRelations { get; set; }
}
When I load the data I just want to select certain kind of properties. Currently my expression looks like this:
Expression<Func<RootVO, RootVO>> selectExpr = m => new RootVO
{
Id = m.Id,
Description = m.Description,
Relation = m.Relation != null ? new RelationVO
{
Id = m.Relation.Id,
Property1 = m.Relation.Property1
} : null
};
var result = context.Roots.Select(selectExpr).ToList();
Is there an easier way to handle the relation select?
Edit
Maybe some background here will help:
I have a huge object with a lot of columns and relations, some with inner, some with outer joins. This query gets accessed by a datagrid on UI which can have dynamic columns depending on the user selection. To increase the performance I've written a class that will build the select expression dynamicly depending on the selected columns. For now it is working, but I'm having trouble when an outer join is null due to null-reference excepction.
The debug view on the expression could look like this:
.New IVA.Core.Data.Models.StockMovementLogVO(){
SequenceNo = $m.SequenceNo,
PostingPeriodId = $m.PostingPeriodId,
TransactionDate = $m.TransactionDate,
FinancialYear = $m.FinancialYear,
FinancialYearPeriod = $m.FinancialYearPeriod,
VoucherDate = $m.VoucherDate,
ItemQuantity = $m.ItemQuantity,
BuCode = $m.BuCode,
LocationStructure = .New IVA.Core.Data.Models.LocationStructureVO(){
Id = ($m.LocationStructure).Id,
Description = ($m.LocationStructure).Description
},
BookingType = .New IVA.Core.Data.Models.BookingTypeVO(){
Id = ($m.BookingType).Id,
Description = ($m.BookingType).Description
},
PartnerStockLocationType = .New IVA.Core.Data.Models.StockLocationTypeVO(){
Id = ($m.PartnerStockLocationType).Id,
Description = ($m.PartnerStockLocationType).Description
},
StockLocationType = .New IVA.Core.Data.Models.StockLocationTypeVO(){
Id = ($m.StockLocationType).Id,
Description = ($m.StockLocationType).Description
}
}
StockLocationType and PartnerStockLocationType are outer joins and if those are null the query fails to execute.
I've now changed my expression builder that it will take care of the outer joins by including a null reference check. The expression now looks like this:
.New IVA.Core.Data.Models.StockMovementLogVO(){
SequenceNo = $m.SequenceNo,
PostingPeriodId = $m.PostingPeriodId,
TransactionDate = $m.TransactionDate,
FinancialYear = $m.FinancialYear,
FinancialYearPeriod = $m.FinancialYearPeriod,
VoucherDate = $m.VoucherDate,
ItemQuantity = $m.ItemQuantity,
BuCode = $m.BuCode,
LocationStructure = .New IVA.Core.Data.Models.LocationStructureVO(){
Id = ($m.LocationStructure).Id,
Description = ($m.LocationStructure).Description
},
BookingType = .New IVA.Core.Data.Models.BookingTypeVO(){
Id = ($m.BookingType).Id,
Description = ($m.BookingType).Description
},
PartnerStockLocationType = .If ($m.PartnerStockLocationType != null) {
.New IVA.Core.Data.Models.StockLocationTypeVO(){
Id = ($m.PartnerStockLocationType).Id,
Description = ($m.PartnerStockLocationType).Description
}
} .Else {
null
},
StockLocationType = .If ($m.StockLocationType != null) {
.New IVA.Core.Data.Models.StockLocationTypeVO(){
Id = ($m.StockLocationType).Id,
Description = ($m.StockLocationType).Description
}
} .Else {
null
}
}
Edit
If anyone is interessted how it looks, I've created a repository where I use the class.
https://github.com/NQuirmbach/DynamicQueryBuilder

Insert constraint failed nFOREIGN KEY constraint failed While Seeding Data

I am trying to Seed some sample Data
public class Condition
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
public int ConditionId { get; set; }
public virtual Condition Condition { get; set; }
}
and in my Seed method..
protected override void Seed(AppContext context)
{
Condition condition1 = new Condition();
condition1.Name = "Cond1";
Entity.Entity newEntity1 = new Entity.Entity();
newEntity1.Name = "Test1";
newEntity1.Condition = condition1;
context.Entities.Add(newEntity1);
Condition condition2 = new Condition();
condition2.Name = "Cond2";
Entity.Entity newEntity2 = new Entity.Entity();
newEntity2.Name = "Test Entity 2";
newEntity2.Condition = condition2;
context.Entities.Add(newEntity2);
context.SaveChanges();
}
I am getting this Exception constraint failed FOREIGN KEY constraint failed, I couldn't figure out what wrong I am doing here.
I tried calling context.SaveChanges() after first insertion too and it went fine. but the error appreared only after second context.SaveChanges() only.
protected override void Seed(AppContext context)
{
Condition condition1 = new Condition();
condition1.Id=1;
condition1.Name = "Cond1";
Entity.Entity newEntity1 = new Entity.Entity();
newEntity1.Name = "Test1";
newEntity1.ConditionId=1
newEntity1.Condition = condition1;
context.Entities.Add(newEntity1);
Condition condition2 = new Condition();
condition2.Id=2
condition2.Name = "Cond2";
Entity.Entity newEntity2 = new Entity.Entity();
newEntity2.Name = "Test Entity 2";
newEntity2.ConditionId=2;
newEntity2.Condition = condition2;
context.Entities.Add(newEntity2);
context.SaveChanges();
}
Hope This works..

Why do I get different values from my EntitySet depending on how I LINQ to it?

In debugging the issue in this thread: InvalidCastException when querying nested collection with LINQ I found out that something is wrong with how my Category EntitySet is populated. After selecteding a Category and throwing this exception to see what's going on I get this:
throw new Exception("CID: " + cat.CategoryID +
" LCID: " + cat.LocalizedCategories.First().LocalizedCategoryID +
" CID from LC: " + cat.LocalizedCategories.First().Category.CategoryID);
CID: 352 LCID: 352 CID from LC: 191
What am I doing wrong that causes CategoryID to have different values depending on how I LINQ to it? It should be 191, and not the same value as the LocalizedCategoryID.
This is the code I use to get the Category:
int categoryId = 352; // In reality this comes from a parameter and is supposed
// to be 191 to get the Category.
var cat = categoriesRepository.Categories.First(c => c.CategoryID == categoryId);
This is my domain object with some unrelated stuff stripped:
[Table(Name = "products")]
public class Product
{
[HiddenInput(DisplayValue = false)]
[Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter a product name")]
[Column]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a description")]
[DataType(DataType.MultilineText)]
[Column(Name = "info")]
public string Description { get; set; }
private EntitySet<Category> _Categories = new EntitySet<Category>();
[System.Data.Linq.Mapping.Association(Storage = "_Categories", OtherKey = "CategoryID")]
public ICollection<Category> Categories
{
get { return _Categories; }
set { _Categories.Assign(value); }
}
}
[Table(Name = "products_types")]
public class Category
{
[HiddenInput(DisplayValue = false)]
[Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public int CategoryID { get; set; }
public string NameByCountryId(int countryId)
{
return _LocalizedCategories.Single(lc => lc.CountryID == countryId).Name;
}
private EntitySet<LocalizedCategory> _LocalizedCategories = new EntitySet<LocalizedCategory>();
[System.Data.Linq.Mapping.Association(Storage = "_LocalizedCategories", OtherKey = "LocalizedCategoryID")]
public ICollection<LocalizedCategory> LocalizedCategories
{
get { return _LocalizedCategories; }
set { _LocalizedCategories.Assign(value); }
}
private EntitySet<Product> _Products = new EntitySet<Product>();
[System.Data.Linq.Mapping.Association(Storage = "_Products", OtherKey = "ProductID")]
public ICollection<Product> Products
{
get { return _Products; }
set { _Products.Assign(value); }
}
}
[Table(Name = "products_types_localized")]
public class LocalizedCategory
{
[HiddenInput(DisplayValue = false)]
[Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public int LocalizedCategoryID { get; set; }
[Column(Name = "products_types_id")]
private int CategoryID;
private EntityRef<Category> _Category = new EntityRef<Category>();
[System.Data.Linq.Mapping.Association(Storage = "_Category", ThisKey = "CategoryID")]
public Category Category
{
get { return _Category.Entity; }
set { _Category.Entity = value; }
}
[Column(Name = "country_id")]
public int CountryID { get; set; }
[Column]
public string Name { get; set; }
}
This (in class Category) looks weird:
[System.Data.Linq.Mapping.Association(Storage = "_LocalizedCategories",
OtherKey = "LocalizedCategoryID" )] // ????
public ICollection<LocalizedCategory> LocalizedCategories
Category has a collection of LocalizedCategorys, which means that in the database the table products_types_localized has a foreign keyCategoryID. That field should be the "OtherKey". How was this mapping generated?

Problems with selecting 2 column values in Linq to Entity

Hi I am trying to select the values of two columns which are second driver and price but I am getting error: Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)
Below is the code:
public IQueryable<Event> GetSecondDriverOption(int eventID)
{
ApextrackdaysEntities entity = new ApextrackdaysEntities();
IQueryable<Event> SecondDriver = from p in entity.Events
where p.ID == eventID
select new{ p.SecondDriver,
p.SecondDriverPrice};
return SecondDriver;
}
Any help or suggestions will be appreciated thnx
You cannot use projection when you expect IQueryable<Event> where Event is your mapped type. You must either select Event :
IQueryable<Event> SecondDriver = from p in entity.Events
where p.ID == eventID
select p;
Or you must create new type and project data to a new type:
public class EventDto
{
public Driver SecondDriver { get; set; }
public Price SecondDriverPrice { get; set; }
}
and redefine your method:
public IQueryable<EventDto> GetSecondDriverOption(int eventID)
{
ApextrackdaysEntities entity = new ApextrackdaysEntities();
IQueryable<EventDto> SecondDriver = from p in entity.Events
where p.ID == eventID
select new EventDto
{
SecondDriver = p.SecondDriver,
SecondDriverPrice = p.SecondDriverPrice
};
return SecondDriver;
}
You cannot return anonymous objects. Try like this:
public IQueryable<Event> GetSecondDriverOption(int eventID)
{
ApextrackdaysEntities entity = new ApextrackdaysEntities();
var seconDriver =
from p in entity.Events
where p.ID == eventID;
select p;
return secondDriver;
}