lundi 19 septembre 2016

How do I delete an item from my database that has two primary keys in asp.net MVC?

Hi guys I recently started getting into asp.net and I am still new to it. I have been working on a project and have hit a wall. Let me first give you some details on my project. I am trying to create a scheduling system with few features one of them being able to add other existing users who has registered as "contacts" with which you can share tasks with.

The user does this by searching for an email of an existing user and if it exist they can add that user as a contact.

Now here is my problem. The adding of a contact and everything works fine however I am having trouble with deleting them. In the index view for the delete action link, I tried both using ContactUserId and ApplicationUserId only to realize that this wont work since it is a association class and has two primary keys. My friend who is very reluctant to help me suggested I should bind the two primary keys but I have no idea how to go about this. Please and thank you for any help.

Controller:

[Authorize]
public class ContactsController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Contacts
    public ActionResult Index()
    {

        IEnumerable<ApplicationUser> users = db.Users.ToList();

        IEnumerable<Contact> contacts = db.Contacts.ToList().Where(c =>     c.ApplicationUserID.Equals(User.Identity.Name));

        List<ApplicationUser> curUsers = new List<ApplicationUser>();

        foreach (var contact in contacts)
        {
            foreach (var user in users)
            {
                if (contact.ContactUserID.Equals(user.UserName))
                {
                    curUsers.Add(user);
                }
            }
        }

        ContactsViewModel cvm = new ContactsViewModel();
        cvm.users = curUsers;
        cvm.contacts = contacts;

        return View(cvm);
    }

    // GET: Contacts/Details/5
    public ActionResult Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }

    // GET: Contacts/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Contacts/Create
    // To protect from overposting attacks, please enable the specific     properties you want to bind to, for 
    // more details see http://ift.tt/1eddaz0.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include =     "ApplicationUserID,ContactUserID,Date")] Contact contact)
    {
        if (!String.IsNullOrWhiteSpace(contact.ContactUserID))
        {

            var count = db.Users.Count(u => u.UserName == contact.ContactUserID);

            if (count != 0)
            {
                contact.ApplicationUserID = User.Identity.Name;
                contact.Date = DateTime.Today; 
                db.Contacts.Add(contact);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            //User already exist error message                        
        }

        return View(contact);
    }

    // GET: Contacts/Edit/5
    public ActionResult Edit(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }

    // POST: Contacts/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://ift.tt/1eddaz0.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ApplicationUserID,ContactUserID,Date")] Contact contact)
    {
        if (ModelState.IsValid)
        {
            db.Entry(contact).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(contact);
    }

    // GET: Contacts/Delete/5
    public ActionResult Delete(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Contact contact = db.Contacts.Find(id);
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }

    // POST: Contacts/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(string id)
    {
        Contact contact = db.Contacts.Find(id);
        db.Contacts.Remove(contact);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

Model:

    public class Contact
{
    [Key]
    [Column(Order = 0)]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string ApplicationUserID { get; set; }

    [Key]
    [Column(Order = 1)]
    [Display(Name = "Contact Email")]
    [Required (ErrorMessage = "Contact email is required")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string ContactUserID { get; set; }

    public DateTime Date { get; set; }
}

Index View:

@model MySchedule.ViewModels.ContactsViewModel

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Add", "Create")
</p>
<table class="table">
<tr>
    <th>
        <!--@@Html.DisplayNameFor(model => model.Date)-->
        First Name
    </th>
    <th>
        Last Name
    </th>
    <th>
        Email Name
    </th>
    <th></th>
</tr>
@{
var users = Model.users;
@foreach (var item in users)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.ActionLink("D", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("X", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}
}
</table>

ViewModel:

 public class ContactsViewModel
{
    public IEnumerable<ApplicationUser> users { get; set; }
    public IEnumerable<Contact> contacts { get; set; }

}

Aucun commentaire:

Enregistrer un commentaire