views:

18

answers:

1

I have the following problem. An object has an address, and this address has a country. To fill a dropdownlist with the available countries in the DB I use a property in the partial class of the object:

public string CountryID {
        get { return this.Addresses.Countries != null ? this.Addresses.Countries.ID.ToString() : null; }
        set { this.Addresses.Countries = Repository.Instance.GetCountryByID(Convert.ToInt32(value)); }
    }

The list itself is generated in the formviewmodel by:

Countries = new SelectList(repository.GetAllCountries(), "ID", "country_name", objectX.CountryID);

and in the view it is used like this:

<%= Html.DropDownList("CountryID", Model.Countries, "--select--")%><%= Html.ValidationMessage("CountryID", "*")%>

The problem

When i create a new object all goes well this way. Before I give a new object to my FormViewModel I create the object, a new (blank) address object and a new (blank) Countries object. This I pass to the view in the FormViewModel and I can create the object as is needed. The problem comes up when I want to edit this object with the same partial form and the same Property, CountryID. It complains there is no address so I have to add

this.AddressReference.Load()

so the property becomes:

public string CountryID {
        get { this.AddressesReference.Load(); return this.Addresses.Countries != null ? this.Addresses.Countries.ID.ToString() : null; }
        set { this.AddressesReference.Load(); this.Addresses.Countries = Repository.Instance.GetCountryByID(Convert.ToInt32(value)); }
    }

But now my Create method does no longer work as at time of creation the object is not yet bound to an object context (it still has to be saved to the DB), and the

this.addressReference.Load() 

is causing troubles.

Question

Is there a way I can use one Form (partial view), and one Property as used above for creation as well as editing the object?


P.S. I'm starting to dislike ADO.net lazy loading in MVC1, I guess this is fixed in MVC2 right?

A: 
public string CountryID {
        get {
            if (this.AddressesReference.EntityKey != null) {
                this.AddressesReference.Load();
            } return this.Addresses.Countries != null ? this.Addresses.Countries.ID.ToString() : null;
        }
        set {
            if (this.AddressesReference.EntityKey != null) {
                this.AddressesReference.Load();
            } this.Addresses.Countries = Repository.Instance.GetCountryByID(Convert.ToInt32(value));
        }
    }

Seems to do what I want, though I consider it kind of ugly. Better options may always be posted here :).

bastijn