EntityFramework and FluentAPI working with ComplexTypes

I am creating a new database model using Entity Framework 4.3 Code-FIrst; using the Fluent API. Below is the dummy model.

So my main object is something and I need to keep track of that. All other items are simple. Typically in a database, I would assign a table like Contact, the primary key and the foregin key for the relationship. However, read more about the Fluent API and complex types , especially in this article , I noticed (I think) that I can let EF take care of linking these objects / tables, and I don't have to worry about them as repositories in my MVC application.

So, notice:

  • Something has one-many with contact
  • Contact has one for many with an address
  • Contact has one-many with PhoenNumber

Knowing this, my confusion is about complex types, because Contact is the Complext type for Somethign and Address and PhoneNumber are complex types for something.

  • How do you establish this relationship in the Fluent API?
  • How can I tell if an address is needed?
  • Using domain management in ASP.NET MVC, would I need to maintain an IContactRepository and an IAddressRepository store in order to push to the controller?

(note that some codes have been omitted for brevity.)

// attempt
void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.ComplexType<Contact>();

    modelBuilder.ComplexType<Contact>().Property(p => p.Address).IsRequired();  // COMPILER ERROR

    modelBuilder.ComplexType<Address>();
    modelBuilder.ComplexType<PhoneNumber>();    
}


// DUMMY MODEL
class Something()
{
    void Something()
    {
        this.Contact = new HashSet<Contact>( );
    }

    DateTime DOB { get; set; }
    int YearsEmployed { get; set; }
    ICollection<Contact> Contact { get; set; }
}

class Contact()
{
    void Contact()
    {
        this.Address = new HashSet<Address>();
    }

    ICollection<Address> Address { get; set; }
}

class Address()
{
        string Street1 { get; set; }
        string Street2 { get; set; }
        string State { get; set; }
        string City { get; set; }
        string Zip { get; set; }
        OptionName OptionName { get; set; }
}

class PhoneNumber()
{
    string Number
    OptionName OptionName { get; set; }
}

class OptionName()
{
    string OptionName { get; set; }
}

      

+3


source to share


1 answer


None of your classes are complex types. Complex types must follow strict rules. They cannot contain navigation properties, and because they are mapped to a table of owning entities, they cannot be represented in any other form other than a one-to-one relationship to their own object.



+6


source







All Articles