Reputation: 330
I am trying to first search the domain ids from a particular table based on tenant and then for the domain id I am looking for domain names in another table and adding in a list. I am getting an error on adding the domain object in my list. My code is as shown below:
public IEnumerable<Domain> GetAllByTenant(Guid tenantId)
{
List<Domain> domains = null;
var ids = _applicationDbContext.TenantDomainMap.Where(x => x.TenantId == tenantId).Select(x => x.DomainId);
foreach (var id in ids)
{
var domain = _applicationDbContext.Domain.Where(x => x.DomainId == id);
domains.Add(domain);
}
return domains;
}
I am getting following errors at domains.Add(domain): 1. The best overloaded method match for 'System.Collections.Generic.List.Add(XXX.Models.Domain)' has some invalid arguments 2. cannot convert from 'System.Linq.IQueryable' to 'XXX.Models.Domain'
Please help me in resolving this issue.
Upvotes: 1
Views: 1855
Reputation:
The Where
method always returns an IQueryable
because it has no way of knowing how many items matched your predicate.
There are 4 potential methods you can add after the Where
call to resolve this problem.
Single: This method expects only one match and it will throw an exception if more than one match was found or if no matches were found.
var domain = _applicationDbContext.Domain.Where(x => x.DomainId == id).Single();
SingleOrDefault:
This method is the same as Single
except that it will return the results of default(T), where T is your type, when no results are found; this is usually null.
var domain = _applicationDbContext.Domain.Where(x => x.DomainId == id).SingleOrDefault();
First: This method will return the first item in the list and will only throw an exception if no matches were found.
var domain = _applicationDbContext.Domain.Where(x => x.DomainId == id).First();
FirstOrDefault:
This method unlike First
will not throw an exception on no matches, instead it works just like SingleOrDefault
and will return the type's default value.
var domain = _applicationDbContext.Domain.Where(x => x.DomainId == id).FirstOrDefault();
Given that you are doing a search on an Id, Single
is probably the correct choice, though depending on your saving logic SingleOrDefault
may be needed.
Upvotes: 3
Reputation: 10374
Try adding a .FirstOrDefault();
to ensure only return the first match returned from the Where
.
foreach (var id in ids)
{
var domain = _applicationDbContext.Domain.Where(x => x.DomainId == id).FirstOrDefault();
domains.Add(domain);
}
Where
returns type IEnumerable
and you need to add a single Domain
type to your list, for each.
Upvotes: 1