Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework and FluentAPI working with ComplexTypes

I am creating a new database model using Entity Framework 4.3 Code-FIrst; using Fluent API. Dummy model is below.

So my main object is Something and I need to keep track of this. All the other items are supplimentary. Normally in a Database I would assign a Table such as Contact, a primary key and a foregin key for relationship. However, reading more about about the Fluent API and Complex Types, especially this article, I have noticed (i think) that I can let EF take care of linking those objects/tables and I don't have to worry about them as Repositories in my MVC app.

So please note:

  • Something has a one to many with Contact
  • Contact has one to many with Address
  • Contact has one to many with PhoenNumber

Knowing this, my confusion lies in the Complex Types because Contact is a Complext Type to Somethign and Address & PhoneNumber are Complex Types to Something.

  • How would I set this relationship in Fluent API?
  • How would I say that Address is required?
  • Using domain driven development in ASP.NET MVC, would I have to maintain a repository of IContactRepository and IAddressRepository to push to a controller?

(please note that some code 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; }
}
like image 843
Tomasz Iniewicz Avatar asked Nov 30 '25 05:11

Tomasz Iniewicz


1 Answers

No neither of your classes is complex type. Complex types must follow strict rules. They cannot contain navigation properties and because they are mapped to the owning entity's table they cannot be represented in any other form than one-to-one relation with owning entity.

like image 108
Ladislav Mrnka Avatar answered Dec 02 '25 04:12

Ladislav Mrnka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!