0

I have to create 2 lists and i am looking for the best practice and eventually oneline syntax!

I am using Entity Framework and I have 3 tables:

public class Position 
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Training 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Association 
{
    public int Id { get; set; }
    public Impact Impact { get; set; }

    public int TrainingId { get; set; }
    public virtual Training Training { get; set; }
    public int PositionId { get; set; }
    public virtual Position Position { get; set; }
}

public enum Impact 
{
    Optional,
    Mandatory
}

I have to select all the training which are mentioned in Association table as mandatory or optional (I mean that must have the column Impact fill with Impact.Optional) and the PositionId is the one that I give it through a parameter or something!

How can I do that?

4
  • What have you tried so far? Commented Jul 2, 2019 at 11:06
  • Is this what you need? var result = db.Asociation.Where(x => x.Impact == Impact.YOUR_IMPACT && PositionId == YOUR_ID); Commented Jul 2, 2019 at 11:11
  • @Matt almost yes and with this, how I can get a collection of Training! Your syntax filters the right "associations" and I want to use TrainingId to take the training list! Commented Jul 2, 2019 at 11:22
  • Check my answer below and try again Commented Jul 2, 2019 at 11:33

2 Answers 2

1

Try this

public List<Training> GetOptionalTrainings(int positionId)
{
  _context.Associations
    .Where(a => a.Impact == Impact.Optional && a.PositionId == positionId)
    .Select(a => a.Training)
    .ToList();
}
Sign up to request clarification or add additional context in comments.

Comments

0

enter image description here

note that your relations are 1-1 ,Association will always have a Training , if you want a 0 or 1 relation you can change public int TrainingId to public int? TrainingId

updated

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.