update element of list of Complex object with linq - linq

Hi everybody and thanks in advance for solution
I've these objects
List<AccessModuleInfo> listOfAccessModuleInfo = new List<AccessModuleInfo>();
public class AccessModuleInfo
{
public int AccessModuleId { get; set; }
public string AccessModuleName { get; set; }
public List<AccessRoleInfo> ListOfAccessRole { get; set; }
}
public class AccessRoleInfo
{
public int AccessRoleId { get; set; }
public string AccessRoleName { get; set; }
public bool AccessRoleValue { get; set; }
}
I receive listOfAccessModuleInfo that is already fill and when I try to update AccessRoleValue in specific AccessModuleInfo, all AccessRoleValue with the same AccessRoleId are updated .
I want update only AccessRoleValue of specific AccessModuleInfo (for example with AccessModuleId = 4)
Thanks

Normally something like this should work just fine:
// You didn't confuse == vs = did you?
// Single also helps us debug and ensure we're only getting one result
var itemToUpdate = listOfAccessModuleInfo.Where(x => x.AccessModuleId == 4).Single();
itemToUpdate.ListOfAccessRole.ForEach(x => x.AccessRoleValue = newValue);

Related

how to use projection in the include extension method in ef core?

I want to able to select certain entity properties (columns from db) in the include statement of queryable object. My query looks like below but I m getting error Lambda expression used inside Include is not valid
var samuraiWithQuotesQueryable = _context.Samurais.AsQueryable()
.Include(s => s.Quotes.Select(x => new { x.Text }));
// additional filters followed by getting the list
var samuraiList = samuraiWithQuotesQueryable.ToList();
Samurai and Quote entities look like below
public class Samurai
{
public Samurai()
{
Quotes = new List<Quote>();
}
public int Id { get; set; }
public string Name { get; set; }
public List<Quote> Quotes { get; set; }
}
public class Quote
{
public int Id { get; set; }
public string Text { get; set; }
public Samurai Samurai { get; set; }
public int SamuraiId { get; set; }
}
Wondering if this is possible with the IQueryable object?

Suggestion field array

I have a document that contains an array of tags. I need to create a suggestion field corresponding to this tag field (to generate tag suggestions based on the values in the tag array). I am using NEST to interact with elastic search mostly. But I am not able to updated the suggestion property. The class used for the document contains following
Document structure:
public class SuggestField
{
public IEnumerable<string> Input { get; set; }
public string Output { get; set; }
public object Payload { get; set; }
public int? Weight { get; set; }
}
public class Source{
[ElasticProperty(Index = FieldIndexOption.NotAnalyzed)]
public string[] tags { get; set; }
public SuggestField[] tag_suggest { get; set; }
}
I add the mapping as follows:
var response = client.Map<Source>(m => m
.MapFromAttributes()
.Properties(p => p
.Completion(c => c
.Name(cp => cp.tag_suggest)
.Payloads()
)));
For updating tags, I use external scripts. I was hoping to change this same script to add changes to tag_suggest field also. But I tried the following but it is not working. Following is the script I tried:
if (ctx._source.tags.indexOf(newTag) < 0) {
ctx._source.tags[ctx._source.tags.length] = newTag;
ctx._source.tag_suggest[ctx._source.tag_suggest.length] = { input :newTag }
}
I would change type of tag_suggest property from SuggestField[] to SuggestField. You can store all tags in SuggestField.Input.
public class Source
{
[ElasticProperty(Index = FieldIndexOption.NotAnalyzed)]
public string[] tags { get; set; }
public SuggestField tag_suggest { get; set; }
}
Regarding your update script, after this change you can modify it to:
if (ctx._source.tags.indexOf(newTag) < 0) {
ctx._source.tags[ctx._source.tags.length] = newTag;
ctx._source.tag_suggest.input[ctx._source.tag_suggest.length] = newTag;
}
Hope it helps.

Retrieving information from derived child object collections using LINQ

I have been trying to get a list of all Workflows that have Offices contained in a certain List by Office Id. I can easily get all of the Workflows that have SingleWorkflowSteps because they have only one Office, but have been unable to understand how I would successfully get those contained in a MultiWorkflowStep. All workflow steps have either a SingleWorkflowStep or a MultiWorkflowStep that contains two or more SingleWorkflowSteps. At the time I designed this, it seemed like a logical way to do this but atlas my LINQ-fu is not as good as I thought it was. Can someone please point me in the right directions. Code listed below:
var OfficesToFind = new List<int> (new int[] { 1,3,5,7,9,10,11,12} );
public class Workflow
{
public Workflow()
{
WorkflowSteps = new List<WorkflowStepBase>();
}
public int Id { get; set; }
public virtual ICollection<WorkflowStepBase> WorkflowSteps { get; set; }
}
public abstract class WorkflowStepBase
{
public int Id { get; set; }
public int StatusId { get; set; }
public virtual Workflow Workflow { get; set; }
public virtual Status Status { get; set; }
}
public class MultiWorkflowStep : WorkflowStepBase
{
public MultiWorkflowStep()
{
ChildSteps = new List<SingleWorkflowStep>();
}
public virtual ICollection<SingleWorkflowStep> ChildSteps { get; set; }
}
public class SingleWorkflowStep : WorkflowStepBase
{
public int? ParentStepId { get; set; }
public int OfficeId { get; set; }
public virtual MultiWorkflowStep ParentStep { get; set; }
public virtual Office Office { get; set; }
}
public class Office
{
public int Id { get; set; }
public string Name { get; set; }
}
public class WorkflowService : IWorkflowService<Workflow>
{
private readonly IRepository<Workflow> _workflowService;
private readonly IRepository<SingleWorkflowStep> _singleStepService;
private readonly IRepository<MultiWorkflowStep> _multiStepService;
public WorkflowService(IUnitOfWork uow)
{
_workflowService = uow.GetRepository<Workflow>();
_singleStepService = uow.GetRepository<SingleWorkflowStep>();
_multiStepSercice = uow.GetRepository<MultiWorkflowStep>();
}
// ~ ------- Other CRUD methods here -------- ~
public IEnumerable<Workflow> GetWorkflowFilter(List<int> statuses, List<int> offices...)
{
var query = _workflowService.GetIQueryable(); // returns an IQueryable of dbset
if(statuses.Any())
{
query = query.Where(q => statuses.Contains(q.StatusId));
}
if(offices.Any())
{
// Get all active single steps and the ones that contain the offices
singleSteps = _singleStepService
.Where(s => s.StatusId == (int)Enumerations.StepStatus.ACTIVE)
.Where(s => offices.Contains(s.OfficeId));
// Get all of the parent Workflows for the singleSteps
var workflows = singleSteps.Select(w => w.Workflow);
// Update the query with the limited scope
query = query.Where(q => q.Workflow.Contains(q));
}
return query.ToList();
}
}
OK, after a good night sleep, being all bright-eyed and bushy-tailed, I figured out my own problem. First the updated code was all wrong. Because each derived WorkflowStep has access to the Workflow and each MultiWorkflowStep contains a list of SingleWorkflowSteps - when I get the list of all SingleWorkflowSteps (which would include all from MultiWorkflowStep(s)), I simply needed to get a list of all of the parent Workflows of the SingleWorkflowSteps. Next I updated my query to limit the Workflows that were contained in the new Workflow list and here is the correct code for the GetWorkflowFilter method:
...
if(offices.Any())
{
// Get all active single steps and the ones that contain the offices
singleSteps = _singleStepService.Where(s => s.StatusId == (int)Enumerations.StepStatus.ACTIVE).Where(s => offices.Contains(s.OfficeId));
// Get all of the parent Workflows for the singleSteps
var workflows = singleSteps.Select(w => w.Workflow);
// Update the query with the limited scope
query = query.Where(q => q.Workflow.Contains(q));
}
return query.ToList();
}

Joining in LINQ to select a sublist within a list

I have two classes as follows:
public class HRM_SERVICE_PERD_BNFT_DTLModel
{
public string SRVC_PERD_BNFT_CODE { get; set; }
public string RTR_BNFT_CODE { get; set; }
public string RTR_BNFT_NAME { get; set; }
public string RTR_BNFT_CALC_MODE { get; set; }
public string SAL_HEAD_CODE { get; set; }
public string SAL_HEAD_NAME { get; set; }
public string RTR_BNFT_IN_PERCENT { get; set; }
public string RTR_BNFT_AMOUNT { get; set; }
public string RTR_BNFT_INACTV_DATE { get; set; }
public short? RTR_BNFT_SLNO { get; set; }
}
public class HRM_RETIREMENT_BENEFITModel : BaseModel
{
public string RTR_BNFT_CODE { get; set; }
public string RTR_BNFT_NAME { get; set; }
public string RTR_BNFT_SRTNM { get; set; }
public string RTR_BNFT_REM { get; set; }
public short? RTR_BNFT_SLNO { get; set; }
}
Now I want to select data from the first model for a specific 'SRVC_PERD_BNFT_CODE', then I need to select the 'RTR_BNFT_NAME' from the second table for all the filtered data along with some other value from the first model. I'm trying kind of joining, but not getting the name. It's showing system.collection.string instead of value.
Here is what I'm trying so far:
public List<HRM_SERVICE_PERD_BNFT_DTLModel> GetBenefitData(string mstcode)
{
var model2 = DataContext.HRM_SERVICE_PERD_BNFT_DTL.AsEnumerable().Where(m => m.SRVC_PERD_BNFT_CODE == mstcode).Select(s=>s).ToList();
var model = DataContext.HRM_SERVICE_PERD_BNFT_DTL.AsEnumerable().Where(m => m.SRVC_PERD_BNFT_CODE == mstcode)
.Select(s => new HRM_SERVICE_PERD_BNFT_DTLModel
{
RTR_BNFT_CODE = s.RTR_BNFT_CODE,
RTR_BNFT_SLNO = s.RTR_BNFT_SLNO,
RTR_BNFT_CALC_MODE = s.RTR_BNFT_CALC_MODE,
RTR_BNFT_AMOUNT = (s.RTR_BNFT_AMOUNT).ToString(),
RTR_BNFT_NAME = (from x in model2
join c in DataContext.HRM_RETIREMENT_BENEFIT on x.RTR_BNFT_CODE equals c.RTR_BNFT_CODE into p
from b in p.AsEnumerable()
select b.RTR_BNFT_NAME).ToList().ToString(),
RTR_BNFT_IN_PERCENT = (s.RTR_BNFT_IN_PERCENT).ToString()
}).ToList();
return model;
}
What I'm doing wrong? Please help.
Following is suspicious.
.ToList().ToString()
Remove the ToString part and replace it with something like FirstorDefault, then it should work.
Reason for getting something like System.Collection.String is that List<T>.ToString() is usually typename until it is overridden in some way.
Following minimal snipped produce System.Collections.Generic.List1[System.String]`
List<String> list = new List<String>();
var str = list.ToString();
Console.WriteLine(str); //System.Collections.Generic.List`1 [ System.String ]

Lambda Expression for Many to Many realtionship in C# EF 5 Code First

I'm using EF 5 Code First and VS 2012.
I have classes for Articles and Tags. Each Article will have atleast one Tag associated.
Please see the classes below.
public class Article
{
public int ArticleId { get; set; }
public virtual ICollection<ArticleTag> Tags { get; set; }
}
public class Tag
{
public int TagId { get; set; }
public string TagName { get; set; }
}
public class ArticleTag
{
public int ArticleId { get; set; }
public int TagId { get; set; }
// navigation property
public virtual Article Article { get; set; }
public virtual Tag Tag { get; set; }
}
Below is the code I tried. requestTags contains the list of TadgIds. repBase is db context. But below code is returing all Articles.
var idList = requestTags.tags.Select(t => t.id).ToList();
var result= repBase.GetAll<Article>().Select(tg => tg.Tags.Where(tk => idList.Contains(tk.TagId))).ToList();
Please hlep me to get list of articles for a given list of TagIds.
Thanks in advance.
I think you are looking for this.
Change:
Select to Where
tg.Tags.Contains to tg.Tags.Any
example:
var idList = requestTags.tags.Select(t => t.id).ToList();
var result= repBase.GetAll<Article>().Where(tg => tg.Tags.Any(tk => idList.Contains(tk.TagId))).ToList();

Resources