简体   繁体   中英

EF7 One to One relationships

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM