简体   繁体   English

EF7一对一关系

[英]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. 我目前正在努力处理新的EF7,在处理一对一关系时遇到了奇怪的问题。

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. 我现在遇到的问题是,当我尝试使用计量单位查询材料时,计量单位始终设置为null,但是当我检查生成的表时,我可以清楚地看到外键是实际创建的。

I've also attempted to force the relationship in the OnModel creating however I'm still unable to retrieve the unit object. 我也曾试图在创建OnModel时强制关系,但是我仍然无法检索该单元对象。

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. 此时的延迟加载在EF7中不起作用。 You'll have to do eager loading (dbContext.Materials.Include(m => m.UnitOfMeasure)) or the explicit version of that. 您必须进行急切的装载(dbContext.Materials.Include(m => m.UnitOfMeasure))或该装载的显式版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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