Valerio
Valerio

Reputation: 3614

Entity Framework 4.1 one to one relationship nullable

Hello everybody again,

I need some help in this logic for EF 4.1 I have one table with data for a customer. I have also another table with a survey i need to compile when needed. So initally i could insert a new customer and after some days I'll fill the survey form. Then the relationship MUST be one-to-one and optional (just because this survey could never be compiled for a customer).

I digged in some examples online but i'm really stuck.

Thank you in advance.

Upvotes: 2

Views: 1023

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

Simply define your entities like:

public class Customer
{
    public int Id { get; set; }
    ...
    public virtual Survey Survey { get; set; }
}

public class Survey
{
    [Key, ForeignKey("Customer")]
    public int Id { get; set; }
    public virtual Customer Customer { get; set; }
}

If you don't like data annotations remove them and place this into OnModelCreating in your context:

modelBuilder.Entity<Customer>()
            .HasOptional(c => c.Survey)
            .WithRequired(s => s.Customer);

Upvotes: 4

Related Questions