MGDavies
MGDavies

Reputation: 1054

Using LINQ to search relational databases

I have the following databases: enter image description here

and the following code:

public IActionResult Index(IssueModel searchCriteria)
{
    var bloods = from m in _context.Blood
                 select m;
    if (!string.IsNullOrEmpty(searchCriteria.SearchComponent))
    {
        //Blood Component
        bloods = bloods.Where(s => s.Component.Contains(searchCriteria.SearchComponent));
        //Blood Type : This is where I plan to search for a specific blood type.
    }
    return View(bloods);
}

As you can see, I'm happy to search the blood database for a certain component type. In the area I've marked I would like to search for blood that relates to a certain PlasType or RedBloodType.

Any ideas? Thanks!

Edit: Thanks to everyone who offered an answer. All the answers I've looked at have been incredibly useful not just in helping me crack this one, but improve my understanding of the topic.

Upvotes: 0

Views: 321

Answers (3)

blogprogramisty.net
blogprogramisty.net

Reputation: 1772

Like this:???

    result = new List<Blood>();

    foreach (var b in bloods)
    {
      if (_context.Donor.Where(d => d.id == b.BloodId)
                        .Any(d => (d.PlasType == "somethingsYouNow") || (d.RedBloodType == "somethingsYouNow"))
      {
        result.Add(b)
      }
    }


    return result;

Upvotes: 1

Tauseef
Tauseef

Reputation: 424

i would just create simple sql query and then convert it to linq query.

Select distinct blood.* from blood
inner join donor on blood.donorid = donor.donorid
where donor.PlasType like 'param' or RedBloodType like 'param'

now convert this to a linq query

var filteredBlood = (from b in blood
                      join d in donor on b.DonorId equals d.DonorId
                      where d.PlasType.contains("param") || d.RedBloodType.contains("param")
                      select b).distinct().toList();

Upvotes: 1

smq93
smq93

Reputation: 94

Don't you have the navigation property like Blood.Donors (if it's one to many relation)? You can access to it via this property but earlier you should include it:

Blood.Include(c => c.Donors);

Upvotes: 1

Related Questions