0

Iam trying to delete Addresses that associate to person before when user delete person I have problem as you see I try to get the person id to delete it from address before delete person error

Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NotSupportedException: Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.

Source Error:

   [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Person person = db.Persons.Find(id);
        var  address = (from u in db.Addresses
                           where u.PersonID.Equals(id)
                           select u.PersonID).SingleOrDefault();
        db.Addresses.Remove(person);
        db.Persons.Remove(person);

        db.SaveChanges();
        return RedirectToAction("Index");
    }
tereško
  • 58,060
  • 25
  • 98
  • 150

3 Answers3

0
Person person = db.Persons.Find(id);
var  address = (from u in db.Addresses where u.PersonID == id).SingleOrDefault();

if(address != null)
    db.Addresses.Remove(address);

db.Persons.Remove(person);

in your example your linq query is pulling data you already have, then you're not using your address variable at all.

You want to remove an address from db.Addresses, not a person. This also assumes there is only one address per person.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
0

I've only had a quick look but I think your issue lies with the following part of your code:

var  address = (from u in db.Addresses
                       where u.PersonID.Equals(id)
                       select u.PersonID).SingleOrDefault();

Try replacing

where u.PersonID.Equals(id)

with

where u.PersonID == id

Hope this works for you!

(Out of interest, if you check out the following Stackoverflow response from LeakyCode, he has clarified the difference between == and Equals: C# difference between == and Equals() )

Community
  • 1
  • 1
Stu1986C
  • 1,452
  • 1
  • 18
  • 34
0

You mentioned you want to delete all addresses belonging to a person, you need to get a list of them and remove them...

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    Person person = db.Persons.Find(id);

    var  addresses = from u in db.Addresses
                   where u.PersonID == id;
    addresses.ToList().ForEach(a => db.Addresses.Remove(a));

    db.Persons.Remove(person);

    db.SaveChanges();
    return RedirectToAction("Index");
}
Anthony Chu
  • 37,170
  • 10
  • 81
  • 71