views:

73

answers:

1

I have 2 related entities: Contact and Address. There is a relation between each other. 1 Contact with 1 Address.

In the create Form, I fill the FirstName and LastName text boxes. I have a field related to the address.

In some situations, I perform an AJAX request to fill automatically the Address Info.

The problem is: when I click save, that creates a new Address entry instead of just associating the contact with the AddressID provide by the AJAX request.

The desired behaviour is that if the AddressID is empty save a new address entry. If the AddressID is NOT empty, just associate it.

<%: Html.TextBoxFor(model => model.ContactInfo.FirstName)%>
<%: Html.TextBoxFor(model => model.ContactInfo.LastName)%>

<%:Html.TextBoxFor(model => model.ContactInfo.Address.AddressID)%>    
<%:Html.TextBoxFor(model => model.ContactInfo.Address.City)%>        
<%:Html.TextBoxFor(model => model.ContactInfo.Address.Street)%>    

How can this be done?


Here is when I save the Entity

public ActionResult Create(Contact ContactInfo){
    try
    {  
        ContactInfo.IsActive = true;
        _db.AddToContacts(ContactInfo);
        _db.SaveChanges();
    }
}
A: 

You mean like:

    ContactInfo.IsActive = true;
    if (ContactInfo.HasValue)
    {
        ContactInfo.Address = _db.Addresses.Single(a => a.AddressID == ContactInfo.Address.AddressID);
    }
    _db.AddToContacts(ContactInfo);
    _db.SaveChanges();

?

With FK associations (optional, in EF 4), you can also do:

    ContactInfo.IsActive = true;
    if (ContactInfo.HasValue)
    {
        ContactInfo.Address = null;
        ContactInfo.AddressID = ContactInfo.Address.AddressID;
    }
    _db.AddToContacts(ContactInfo);
    _db.SaveChanges();
Craig Stuntz
I Use FK and EF 4. My concern is when I populate the Address info with an ajax Request and press Save Button, it's save a new entry instead of just make an association of the AddressID filled with the ajax response.
Jean-Francois
I understand. Did you try my suggestion(s)?
Craig Stuntz
Thanks, it's working. The trick is to set the Address To Null when you don't want to save a new address.
Jean-Francois