0

I have 2 models, Registration and RegistrationCode. A registration may have a single registration code and a registration code may have a single registration.

public class Registration
{
    public Registration()
    {
        RegistrationDate = System.DateTime.Now;
    }
    [Key]
    public int RegistrationID { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime? RegistrationDate { get; set; }


    public RegistrationCode RegistrationCode { get; set; }
}

public class RegistrationCode
{
    [Key]
    public string Code { get; set; }

    public bool IsUsed { get; set; }

    public Registration Registration { get; set; }
}

I've tried mapping the association with Fluent API like so:

    modelBuilder.Entity<Registration>()
        .HasOptional(t => t.RegistrationCode)
        .WithOptionalPrincipal();

But the problem is when I recreate my database with update-database, my RegistrationCode table has the following fields which suggests something is not right:

Code    nvarchar(50)    Unchecked
IsUsed  bit Unchecked
Registration_RegistrationID int Checked
Registration_RegistrationID1    int Checked

Can someone suggest how I should do this?

Phill
  • 18,398
  • 7
  • 62
  • 102
Evonet
  • 3,600
  • 4
  • 37
  • 83

2 Answers2

0

This would make the one to one or zero relationship between entities.

 modelBuilder.Entity<Registration>()
    .HasRequired(m => m.RegistrationCode)
    .WithOptional(t => t.Registration)

For more details over relatonship please follow the MSDN

Ashish Rajput
  • 1,489
  • 1
  • 11
  • 20
  • As I mentioned in the question, both registrations and registration codes are optional, so HasRequired won't work here – Evonet Jul 13 '14 at 00:02
0

By your code

modelBuilder.Entity<Registration>()
            .HasOptional(t => t.RegistrationCode)
            .WithOptionalPrincipal();

you tell EF that there is a principal (Registration) of which the association is not part of the model. Besides that, there is the Registration property in RegistrationCode. EF takes this as a second foreign key. The fix is to tell EF that both are the same:

modelBuilder.Entity<Registration>()
            .HasOptional(t => t.RegistrationCode)
            .WithOptionalPrincipal(r => r.Registration);
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291