使用Linq和QueryExpression选择JOIN表

时间:2018-11-07 11:37:55

标签: c# sql .net linq dynamics-crm

我有这个:

QueryExpression query = new QueryExpression("entity1");
query.ColumnSet = new ColumnSet(true);

LinkEntity accountLink = query.AddLink("entity2", "entity1id", "entity1id", JoinOperator.Inner);
accountLink.Columns = new ColumnSet(true);
accountLink.EntityAlias = "e2";

...

EntityCollection entities = service.RetreiveMultiple(query);

让我们说query中有更多的联接和条件,但是对我们来说,重要的是JOIN。 现在,我想从IEnumerable<Entity>获得具有entity2个实例的query。我该怎么做?我正在考虑使用Linq,但我不知道如何出色地编写命令。我想要这样的东西:

IEnumerable<Entity> entities2 = from entity in entities.Entities
                                          ?? e2 ???
                                          select ??;

1 个答案:

答案 0 :(得分:0)

这是一个D365 LINQ查询示例,其中包括具有后期绑定实体的联接:

public JsonResult Offices()
{    
    var connectionString = @"SET YOUR CONNECTION STRING";
    var svc = new CrmServiceClient(connectionString); 
    var list = new List<KeyValuePair<Guid, string>>();
    using (var context = new Microsoft.Xrm.Sdk.Client.OrganizationServiceContext(svc))
    {           
        var result = (from a in context.CreateQuery("account")
                      join o in context.CreateQuery("opportunity")
                      on a.GetAttributeValue<Guid>("accountid") equals o.GetAttributeValue<Guid>("new_igoffice")
                      where a.GetAttributeValue<OptionSetValue>("statecode").Value == 0
                      where o.GetAttributeValue<Guid>("parentaccountid") != Guid.Empty
                      orderby a.GetAttributeValue<string>("name")
                      select new KeyValuePair<Guid, string>(a.GetAttributeValue<Guid>("accountid"), a.GetAttributeValue<string>("name")))
                      .Distinct();

        list.AddRange(result);
    }
    return Json(list, JsonRequestBehavior.AllowGet);
}