1

one for customer, and one for address.

Required Functionality When a customer registers, they enter their personal details such as name, tel as well as their address details in the same view.

Current Functionality At present, EF scaffolding provides a dropdown list of addresses to choose from.

Current Code

public class Customer
{
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    [Required]
    public string Surname { get; set; }
    [Required]

    ...
    Customer Fields
    ...

    public int AddressId { get; set; }

    public virtual Address Address { get; set; }
}

public class Address
{
    [Key]
    public int AddressId { get; set; }

    ...
    Address Fields
    ...

    // Navigation Properties
    public virtual List<Customer> Customer { get; set; }
}

When seeding the database, I can do so as follows:

new List<Customer>
    {
        new Customer 
            { 
                ** Customer Fields ** , 
                Address = new Address { ** Address Fields ** }
            }
    }.ForEach(c => context.Customers.Add(c));
base.Seed(context);

My thoughts

My initial thoughts are that I should create a 3rd Data model called CustomerWithAddress which is essentially a composite of customer and address models. This would allow me to scaffold a strongly typed view.

Alternatively, is it possible for a controller to pass 2 models to 1 view?

I don't know if this is the best way of tackling this problem, or in fact if it is possible. Any thoughts?

Gravy
  • 12,264
  • 26
  • 124
  • 193

1 Answers1

0

If your customer model has an address property, then you will be able to access it from your view. e.g.

@Html.DisplayTextFor(x => model.Address.Addressline1)

Your viewmodel Idea is a good one, but it's not necessary for this particular case.

EDIT: As my friend below pointed out, you may need to manually load the Address property if you are employing lazy loading.

Captain Kenpachi
  • 6,960
  • 7
  • 47
  • 68
  • This may require use of `.Include()` to actually load the `Address` property; if EF is lazy-loading things then `model.Address` may be null when it gets to the view. – anaximander Jun 03 '13 at 13:59