Hi to get associated records from campaignlist_association in ms crm 2013. Tried tons of different variations.
This is last one:
System.Guid campaignId = ((EntityReference)entity.Attributes["regardingobjectid"]).Id;
var list = (from c in EntityCon.CampaignSet
join l in EntityCon.ListSet on c.campaignlist_association equals l.campaignlist_association
where c.CampaignId == campaignId select c).First();
The error message
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'
indicates that the types of the properties used with the equals expression must match, e.g. that they are both Int32 or Guid.
Make sure that the type l.campaignlist_association is the same as the type c.campaignlist_association.
I would use code as follows to get the associated entity records. Change the column set as per your requirement.
private EntityCollection GetAssociatedEntityItems(string relationshipName, string relatedEntityName, string entityName, Guid entityId)
{
EntityCollection result = null;
QueryExpression query = new QueryExpression();
query.EntityName = relatedEntityName;
query.ColumnSet = new ColumnSet(false);
Relationship relationship = new Relationship();
relationship.SchemaName = relationshipName;
relationship.PrimaryEntityRole = EntityRole.Referencing;
RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
relatedEntity.Add(relationship, query);
RetrieveRequest request = new RetrieveRequest();
request.RelatedEntitiesQuery = relatedEntity;
request.ColumnSet = new ColumnSet(true);
request.Target = new EntityReference
{
Id = entityId,
LogicalName = entityName
};
RetrieveResponse response = (RetrieveResponse)serviceProxy.Execute(request);
RelatedEntityCollection relatedEntityCollection = response.Entity.RelatedEntities;
if (relatedEntityCollection.Count > 0)
{
if (relatedEntityCollection.Values.Count > 0)
{
result = (EntityCollection)relatedEntityCollection.Values.ElementAt(0);
}
}
return result;
}
Related
So I have the list that I want to join against a table on the db.
I am getting the error Unable to create a constant value of type, what am I doing wrong?
List<info.user> studyAccessList = new List<info.User>();
using (var Db = new Entities())
{
//get users from USER table
var UserDbQry = (from data in Db.USER
where data.System == "something" & data.Active == true
select data);
//outer join
var joinQry =
from s1 in UserDbQry
join t2 in studyAccessList
on new
{
Study = s1.Study,
Email = s1.Email
}
equals new
{
Study = t2.Study,
Email = t2.Email
}
into rs
from r in rs.DefaultIfEmpty()
//where r == null
select s1;
foreach (var inactiveUser in joinQry)
{
//add tag for system.
//create xml
string xml = String.Format("<User><Study>{0}</Study><Email>{1}</Email><Active>false</Active></User>", inactiveUser.Study, inactiveUser.Email);
recordCount = recordCount + ProcessXml(wsu, xml, log.ErrorMsgPrefix);
}
}
I needed to change the first query to a list then the second query was able to pick it up.
//get users from USER table
var UserDbQry = (from data in Db.USER
where data.System == "something" & data.Active == true
select data).ToList;
//outer join
var joinQry =
from s1 in UserDbQry
join t2 in studyAccessList
on new
{
Study = s1.Study,
Email = s1.Email
}
equals new
{
Study = t2.Study,
Email = t2.Email
}
into rs
from r in rs.DefaultIfEmpty()
//where r == null
select s1;
I am currently using Linq to join two tables together, mainTable and selectTable, they are joined on mainTable.ID = selectTable.mtID. I am trying to include a third table, myTable, that is joined on selectTable.ID = myTable.selID. There will be many records in myTable for one ID from selectTable so I'm trying to get List<myTable>. This is what I have so far that works:
public async Task<List<mainTableDto>> listAll()
{
var db = _repository.DbContext;
var result = await ( from mt in db.mainTable
join sel in db.selectTable
on mt.ID equals sel.mtID
select new mainTableDto
{
ID = mt.ID,
createDate = mt.createDate,
selectTable = new selectTableDto
{
ID = sel.ID
name = sel.name
}
}
}).ToListAsync;
return result;
I've tested getting data from selectTableDto with List< myTableDto> and it works.
I'm a little stuck on how to include a List<myTableDto> into this nested call. I've tried:
join sel in db.selectTableInclude(x=>x.myTableDto)
But when I do this I don't get the info from myTableDto and just get null instead (I've put data in the DB so there should be something)
I've also tried:
join sel in db.selectTable
on mt.ID equals sel.mtID
join my in db.myTable
on sel.ID equals my.selID
selectTable = new selectTableDto
{
ID = sel.ID
name = sel.name
myTableDto = new List<myTableDto>
{
ID = my.ID
}
}
But when I do this it says "ID is not a member of myTableDTO".
Any advice on what I'm doing wrong?
I believe you want a groupjoin (method syntax) or into (query syntax)
This is query syntax:
from mt in db.mainTable
join sel in db.selectTable
on mt.ID equals sel.mtID
into mainTableSels
select new mainTableDto
{
ID = mt.ID,
createDate = mt.createDate,
selectTable = from mts in mainTableSels select new selectTableDto
{
ID = mts.ID
name = mts.name
}
}
Though I do personally prefer a hybrid query/method syntax:
from mt in db.mainTable
join sel in db.selectTable
on mt.ID equals sel.mtID
into mainTableSels
select new mainTableDto
{
ID = mt.ID,
createDate = mt.createDate,
selectTable = mainTableSels.Select(mts => new selectTableDto
{
ID = mts.ID
name = mts.name
})
}
I'm not clear on what type your mainTableDto.selectTable property is; if it's an array or list you'll need a ToArray/ToList. If it's IEnumerable then it should work without
I need to build a search query with dynamic parameters in net core 3.0.
IQueryable<UserDto> query =
from user in dbContext.DB_USER
join items in dbContext.DB__ITEMS on user.IdItem equals items.IdItem
join cars in dbContext.DB_CARS on user.IdCars equals cars.IdItem
join statsCar in dbContext.DB_STATS_CARS on cars.IdCars equals statsCar.Id
select new UserDto
{
Id = user.Id,
Name = user.Name,
Data = user.Data.HasValue ? user.Data.Value.ToUnixTime() : default(long?),
Lvl = user.L,
Items = new ItemsUdo
{
Id = items.Id,
Type = items.Type,
Value = items.Value
},
Cars = new CarsDto
{
Id = cars.Id,
Model = cars.model,
Color = cars.Color
}
};
I would like to add search parameters like user name, items type, cars model and data from user. I tried to add "where" before 'select new UserDto' but not always user will provide all search parameters. If I give below:
if(fromSearch.UserName != null && fromSearch.UserName.Lenght > 0)
{
query = query.Where(u => u.Name == fromSearch.UserName);
}
it works(on user.data does not work) but is it correct? How to do this in linq query?
Do something like this:
IQueryable<UserDto> query =
from user in dbContext.DB_USER
join items in dbContext.DB__ITEMS on user.IdItem equals items.IdItem
join cars in dbContext.DB_CARS on user.IdCars equals cars.IdItem
join statsCar in dbContext.DB_STATS_CARS on cars.IdCars equals statsCar.Id;
select new UserDto
{
Id = user.Id,
Name = user.Name,
Data = user.Data.HasValue ? user.Data.Value.ToUnixTime() : default(long?),
Lvl = user.L,
Items = new ItemsUdo
{
Id = items.Id,
Type = items.Type,
Value = items.Value
},
Cars = new CarsDto
{
Id = cars.Id,
Model = cars.model,
Color = cars.Color
}
};
if(!string.IsNullOrWhitespace(username))
query = query.Where(ud => ud.Name == username);
if(!string.IsNullOrWhitespace(itemtype))
query = query.Where(ud => ud.Items.Any(i => i.Type == itemtype));
if(!string.IsNullOrWhitespace(carmodel))
query = query.Where(ud => ud.Cars.Any(c => c.Model == carmodel));
etc. These will work like AND; if you specify a username and an itemtype you get only those users named that, with that item type somewhere in the items list.. etc
I've looked around for multiple solutions, but non seemed to work. I aim using a LINQ query to get data and populate an object, however; when I try to assign result to the a ReponseObj I get
Only parameterless constructors and initializers are supported in LINQ to Entities.
The constructor for ObjVO is parameterless.
public static ApiResponseObject<ObjVO> GetObjVO(int ID)
{
ApiResponseObject<ObjVO> response = new ApiResponseObject<ObjVO>();
Context ctx = new Context();
var myQuery = from cb in ctx.tblBlock
join eve in ctx.tblEvent on cb.eventID equals eve.eventID
where cb.BlockID == ID
select new ObjVO
{
Id = cb.BlockID,
Name = cb.BlockHeadline,
TotalTYProjectedSales = cb.totalTYProjectedSale.Value,
StoreTYProjectedSales = cb.storeTYProjectedSale.Value,
SiteTYProjectedSales = cb.storeTYProjectedSale.Value,
ModifiedBy = cb.LAST_UPD_USER_ID,
LastModifiedDate = cb.LAST_UPD_TS,
StoreUnitsOnHand = cb.storeUnitsOnHand.Value,
AssignedCutsCount = 0,
BlockHeadline = cb.contentBlockHeadline,
BelongsToLockedAd = false,
ProductLevel = 1,
SiteAvailability = false,
};
response.responseData = myQuery.FirstOrDefault();
}
This might be because EF cannot translate your query into a SQL statement.
See this for reference.
I have an Entity model with Invoices, AffiliateCommissions and AffiliateCommissionPayments.
Invoice to AffiliateCommission is a one to many, AffiliateCommission to AffiliateCommissionPayment is also a one to many
I am trying to make a query that will return All Invoices that HAVE a commission but not necessarily have a related commissionPayment. I want to show the invoices with commissions whether they have a commission payment or not.
Query looks something like:
using (var context = new MyEntitities())
{
var invoices = from i in context.Invoices
from ac in i.AffiliateCommissions
join acp in context.AffiliateCommissionPayments on ac.affiliateCommissionID equals acp.AffiliateCommission.affiliateCommissionID
where ac.Affiliate.affiliateID == affiliateID
select new
{
companyName = i.User.companyName,
userName = i.User.fullName,
email = i.User.emailAddress,
invoiceEndDate = i.invoicedUntilDate,
invoiceNumber = i.invoiceNumber,
invoiceAmount = i.netAmount,
commissionAmount = ac.amount,
datePaid = acp.paymentDate,
checkNumber = acp.checkNumber
};
return invoices.ToList();
}
This query above only returns items with an AffiliateCommissionPayment.
I'm not sure if EF supports this (nor am I sure if you are using EF2 or EF4), but this is the solution in Linq2Sql so it might be worth trying:
using (var context = new MyEntitities())
{
var invoices = from i in context.Invoices
from ac in i.AffiliateCommissions
join acp in context.AffiliateCommissionPayments on ac.affiliateCommissionID equals acp.AffiliateCommission.affiliateCommissionID into acp_join
from acp_join_default in acpg.DefaultIfEmpty()
where ac.Affiliate.affiliateID == affiliateID
select new
{
companyName = i.User.companyName,
userName = i.User.fullName,
email = i.User.emailAddress,
invoiceEndDate = i.invoicedUntilDate,
invoiceNumber = i.invoiceNumber,
invoiceAmount = i.netAmount,
commissionAmount = ac.amount,
datePaid = acp.paymentDate,
checkNumber = acp.checkNumber
};
return invoices.ToList();
}
The main change here is the into acpg after your join, and the DefaultIfEmpty line.
It's almost always a mistake to use join in LINQ to SQL and LINQ to Entities.
Guessing that the association from AffiliateCommission to AffiliateCommissionPayment is called Payment, you can just do:
using (var context = new MyEntitities())
{
var invoices = from i in context.Invoices
from ac in i.AffiliateCommissions
where ac.Affiliate.affiliateID == affiliateID
select new
{
companyName = i.User.companyName,
userName = i.User.fullName,
email = i.User.emailAddress,
invoiceEndDate = i.invoicedUntilDate,
invoiceNumber = i.invoiceNumber,
invoiceAmount = i.netAmount,
commissionAmount = ac.amount,
datePaid = (DateTime?) ac.Payment.paymentDate,
checkNumber = (int?) ac.Payment.checkNumber
};
return invoices.ToList();
}
LINQ to SQL and LINQ to Entities will both coalesce nulls. The casts are necessary because the inferred type will be based on the type of AffiliateCommissionPayment.paymentDate, which might not be nullable. If it is, you don't need the cast.