views:

62

answers:

1

I've got a ToDo class which has properties for Staff and Priority. If a user updates a ToDo item, changes the TaskName and maybe sets a new Priority how do I update the Priority property -

public class ToDo : BaseEntity
{
    public DateTime? DueDate { get; set; }
    public String Notes { get; set; }
    public virtual Priority Priority { get; set; }
    public virtual Staff Staff { get; set; }
    public String TaskName { get; set; }
}

In my WinForms code I have the following save method:

private void Save()    
{    
    var todo = new ToDo    
    {    
        ID = ToDoID,    
        Staff = ddlStaff.SelectedValue,    
        Priority = ddlPriority.SelectedValue,    
        TaskName = txtTaskName.Text.Trim(),
        Notes = txtNotes.Text.Trim(),
        DueDate = String.IsNullOrEmpty(txtDueDate.Text) ? DateTime.Now : DateTime.Parse(txtDueDate.Text.ToString())
};

 _todoController.SaveOrUpdate(todo);

}

The UI has drop down / combo lists for Staff and Priority, but ddlPriority.SelectedValue isn't a Priority object. I could call the database passing the SelectedValue to return the Priority object and then pass that into the ToDo object but that seems crazy just to create/maintain the relationship between the ToDo item and it's priority.

A: 

You could also instead have an extra property called PriorityId that you set and get. This is a very common scenario in web apps since they're stateless.

EDIT: You can also do something like this:

var selectedStaff = new Staff();
selectedStaff.Id = 2;
context.Staff.Attach(selectedStaff); // The important part.

var todo = new ToDo    
{    
    ID = ToDoID,    
    Staff = selectedStaff,
    Priority = ddlPriority.SelectedValue,    
    TaskName = txtTaskName.Text.Trim(),
    Notes = txtNotes.Text.Trim(),
    ....
}

context.SaveChanges();

Calling context.Staff.Attach(someStaffObject) basically adds the staff object to the context to allow it to be referenced. You have to be sure that you set the key property before calling Attach().

TheCloudlessSky
Typically I use the fk (PriorityID) approach, but all the examples seem to just have the entity referenced rather than Id and I wanted to see how that worked out for me. Being able to query against the entity is a nice benefit - but a round trip to the database just to update the ToDo concerns me. I've also got a Staff relationship so that's going to be another trip and this is a 'simple' object with only 2 relationships, what about those that are more complex?
Simon Martin
@Simon - Most examples have the reference approach because they're examples. They're not tailored for real world scenarios. A more "complex" object would still use the PK/FK approach I described above. See my edit above for another way (which might be what you're trying to do).
TheCloudlessSky