Take the following EF Class:
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public IEnumerable<Property> Property { get; set; }
}
public class Property
{
public int ID { get; set; }
public string Name { get; set; }
public bool Lock { get; set; }
public Person Person { get; set; }
public int PersonID
}
I can pretty much make everything work as expected - including a delete action for Person that also deletes all their property. However, as my code gets more complicated, I want to make the logic slightly more advanced.
In the above example, we have something elsewhere that will set the bool lock for property. In this case, I want to disable delete on person when any property for that person has a lock of true.
The default Delete controller code has:
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var person = await _context.People
.FirstOrDefaultAsync(m => m.ID == id);
if (person== null)
{
return NotFound();
}
return View(person);
}
And the Delete confirm has:
public async Task<IActionResult> DeleteConfirmed(int id)
{
var person= await _context.people.FindAsync(id);
_context.people.Remove(person);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
I know the code to do what I want is:
foreach (var item in person.Property)
{
if item.locked==true
return("error")
}
Now the fun stars! - The old EF4 virtual keyword on properties I'm used to doesn't work - so, I can't iterate over the property because it is currently null. in most instances, I have to call .include()
On the first delete, this modifies:
var person = await _context.People
.FirstOrDefaultAsync(m => m.ID == id);
to
var person = await _context.People.Include(x=>x.property)
.FirstOrDefaultAsync(m => m.ID == id);
which seems to work fine.
However, the second one:
var person = await _context.people.FindAsync(id);
doesn't seem to work. The moment I put the .Include
in, it states error CS1061 that there is no definition for FindAsync.
In all honesty, I am not too sure what the need is for two different ways of looking at an ID in the first place... I can only assume that when looking for an ID in the first delete that may not exist, firstordefault
is the best and when confirming a delete, find
is best.... however, this is what the scaffolding does and I don't feel I know enough to question this.
I however want to be a better developer and would love to understand what is wrong with the code and for future, how do I know what can be combined and what can't as I don't feel I am learning here, I am just randomly trying different things until I find one combination that works.