Alfredo Fernández
Alfredo Fernández

Reputation: 200

Ef Code first One to one relationship with id as foreign

I'm traying to do a mapping with One to One relationship with id as "foreign", I can't change the database

Those are the tables

Cutomer

CustomerDetail

Entity Splittitng does not works for me since i need a left outter join. Any Ideas?

Thanks in advance, and sorry about my english.

Upvotes: 0

Views: 113

Answers (1)

Eranga
Eranga

Reputation: 32437

You can use the Shared Primary Key mapping here.

public class Customer
{
    public int CustomerId { get; set; }

    public string Name { get; set; }

    public virtual CustomerDetail CustomerDetail { get; set; }
}

public class CustomerDetail
{
    public int CustomerId { get; set; }

    public string Details { get; set; }

    public virtual Customer Customer { get; set; }
}

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<CustomerDetail>().HasKey(d => d.CustomerId);

        modelBuilder.Entity<Customer>().HasOptional(c => c.CustomerDetail)
            .WithRequired(d => d.Customer);
    }
}

Upvotes: 1

Related Questions