0
votes

I have seen many examples of implementing a one to one relationship, but I failed doing mine, because the requirements are some kind different (Guid with database generated option, foreign key property and so on).

I have 2 classes (Bundesland, Programmkonfiguration) that have a 1:1 relationship (both ends are required in business sense) but cannot be joined into one table

Requirements to Bundesland:

  • Guid Id as Key but without a DatabaseGenerated Attribute
  • Navigation Property Programmkonfiguration

Bundesland.cs:

public class Bundesland
{
    [Key]
    public Guid Id { get; set; }

    public virtual Programmkonfiguration Programmkonfiguration { get; set; }
}

Requirements to Bundesland

  • Guid Id as Key generated from Database
  • ForeignKey Property Bundesland_Id (needed with _ for interface)
  • Navigation Property Bundesland

Programmkonfiguration.cs:

public class Programmkonfiguration
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public Guid Bundesland_Id { get; set; }

    public virtual Bundesland Bundesland { get; set; }
} 

database schema should look like this

  • table Bundesland (Id)
  • table Programmkonfiguration (Id, Bundesland_Id)

Why I failed until now:

  • EF doesn’t recognize the relationship by itself
  • if I use either attributes (ForeignKey, Required) or fluent API and the mode builder is not failing, the foreign key property Programmkonfiguration.Bundesland_Id is never set, after context.SaveChanges()

If you want to help me, here are additional classes you may gonna need: https://gist.github.com/anonymous/9cb554cd864e3dbee1ac

I am using .NET 4.5(.1) with EF5, but I failed with EF6 too

Thanks in advance :)

1

1 Answers

0
votes

You can use fluent configuration for this:

public class Bundesland
{
    [Key]
    [ForeignKey("Programmkonfiguration")]
    public Guid Id { get; set; }

    public virtual Programmkonfiguration Programmkonfiguration { get; set; }
}

public class BundesLandConfiguration: EntityTypeConfiguration<Bundesland>
{
    public BundesLandConfiguration()
    {            
        HasProperty(p=>p.Id)
        HasRequired(p=>p.Programmkonfiguration).WithRequiredPrincipal(p=>p.Bundesland);
    }
}

public class Programmkonfiguration
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

    public Guid Bundesland_Id { get; set; }

    public virtual Bundesland Bundesland { get; set; }
}

public class ProgrammkonfigurationConfiguration: EntityTypeConfiguration<Programmkonfiguration>
{
    public ProgrammkonfigurationConfiguration()
    {
        HasKey(p=>p.Id);
        HasProperty(p=>p.Id)
        HasProperty(p=>p.Bundesland_Id)
    }
}

Do not forget to add this configurations to EntityModelConfigurations in db context.

Update: because property naming is against convention, you should add [ForeignKey] attribute as I added to property Id of Bundesland class.