I have two tables, Clients
and Physicians
. Each Client
has a list of primary keys for their physicians (PhysicianIds
), which is flattened to a comma-delimited string for database storage (PhysicianStore
).
One of my action methods requires finding which client a physician belongs to, but I can't find a way to do this without evaluating the entire table with .ToList()
. The below code doesn't work because .Split()
doesn't work with LINQ-to-Entities.
Do I need to add a foreign key to Physician
?
// Data model / DTO
public class ClientModel
{
public List<int> PhysicianIds { get; set; }
public string PhysicianStore
{
get { return string.Join(",", PhysicianIds.ConvertAll<string>(i => i.ToString())); }
set { PhysicianIds = value.Split(',').Select(str => int.Parse(str)).ToList(); }
//set { PhysicianIds = value.Split(',').ToList().ConvertAll<int>(str => int.Parse(str)); }
}
}
public class PhysiciansController
{
// Disposed in full code
private MyDbContext db = new MyDbContext();
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return HttpError(HttpStatusCode.BadRequest);
}
PhysicianModel pm = await db.Physicians.FindAsync(id);
if (pm == null)
{
return HttpError(HttpStatusCode.NotFound);
}
// Have to use PhysicianStore here because PhysicianIds is not a column in the DB
return View(new PhysicianDetailsViewModel(pm, db.Clients.Where(c => c.PhysicianStore.Split(',').Contains(pm.Id.ToString()))
.FirstOrDefault()?.Name));
}
}
Edit: Per comments, I really should be using navigation properties. I'll pursue this and ask another question if needed.