EF7 One to One relationships

788 views Asked by At

I'm currently working on getting a handle on the new EF7 and I am running into an odd behaviour when dealing with one to one relationships.

I have the following models

public class Material
{
    [Key]
    [Required]
    [Column(TypeName = "bigint")]
    public long Id { get; set; }

    [Required]
    [MaxLength(128)]
    public string Name { get; set; }

    [Required]
    [MaxLength(512)]
    public string Description { get; set; }

    [Required]
    [Column(TypeName = "money")]
    public decimal CostPerUnit { get; set; }

    public virtual Unit UnitOfMeasure { get; set; }

    [Required]
    [Column(TypeName = "bit")]
    public bool IsActive { get; set; } = false;
}


public class Unit
{
    [Key]
    [Column(TypeName = "bigint")]
    public long Id { get; set; }

    [Required]
    [MaxLength(32)]
    public string Name { get; set; }

    [Required]
    [MaxLength(64)]
    public string Description { get; set; }

    [Required]
    public string Type { get; set; }
}

and I am building the tables as follows:

 builder.Entity<Unit>().Key(u => u.Id);
builder.Entity<Unit>().Property(u => u.Name).MaxLength(64).Required();
builder.Entity<Unit>().Property(u => u.Description).Required();
builder.Entity<Unit>().Property(u => u.Type).Required();

builder.Entity<Material>().Key(m => m.Id);
builder.Entity<Material>().Property(m => m.Name).Required();
builder.Entity<Material>().Property(m => m.Description).Required();
builder.Entity<Material>().Property(m => m.CostPerUnit).Required();
builder.Entity<Material>().Property(m => m.IsActive).Required();

The problem that I'm having is now that when I try and query for a material with a unit of measure, the unit of measure is always set to null, but when I check the generated tables I can clearly see that the foreign key is actually created.

I've also attempted to force the relationship in the OnModel creating however I'm still unable to retrieve the unit object.

builder.Entity<Material>().Reference(m => m.UnitOfMeasure).InverseReference().ForeignKey<Unit>(u => 

How should I be adding this reference or is this even supported yet?

1

There are 1 answers

1
JonTheMon On BEST ANSWER

How are you trying to get the reference? Lazy loading at this point does not work in EF7. You'll have to do eager loading (dbContext.Materials.Include(m => m.UnitOfMeasure)) or the explicit version of that.