填写导航属性?

时间:2016-06-06 05:06:09

标签: entity-framework

我是EF的新手,在我的代码第一个模型中,这是我的Locality类:

public class Locality : ILocality
{
    public int ID { get; set; }
    [Required]
    [MaxLength(150)]
    [Display(Name = "Locality")]
    public string Description { get; set; }
}

这是我的学校课程,我上面有一个导航属性Locality,它是一个1-1的关系:

public class School : ISchool
{
    public int ID { get; set; }
    [Required]
    [MaxLength(150)]
    [Display(Name = "School")]
    public string Description { get; set; }
    [Required]
    [Display(Name = "Locality")]
    public int LocalityID { get; set; }

    public virtual ILocality Locality { get; set; }
}

现在,在我的学校控制器中,我的解决方案如下:

    public ActionResult SchoolList()
    {
        var allschools = schools.GetAll();
        foreach (var school in allschools)
        {
            school.Locality = localities.GetById(school.LocalityID);
        }

        return View(allschools);
    }

我的问题是,当我需要访问导航属性Locality并且我总是必须使用上面的代码填充时,它们将为null:

        foreach (var school in allschools)
        {
            school.Locality = localities.GetById(school.LocalityID);
        }

我读过如果有外键设置,应该自动填写导航属性?如果是这样,我该怎么做?

1 个答案:

答案 0 :(得分:1)

导致Locality属性的类型为ILocality,而不是Locality。并且EF不会将LocalityIDLocality属性视为导航,即FK,因此Locality实体不会自动加载,因为ILocality是接口,即抽象,可以由很多类实现,每个类都有自己的属性(列),名称等,因此EF很困惑,不知道该做什么,结果如何它忽略了这个属性。要修复它,只需将类型从接口替换为类:

public class School : ISchool
{
    //other stuff...

    //public virtual ILocality Locality { get; set; }
    public virtual Locality Locality { get; set; }
}
  

P.S。如果ISchool界面有memeber:ILocality Locality { get; set; },您可以这样做:

public class School : ISchool
{                
    //other stuff...
    [ForeignKey("LocalityDB")]
    public int LocalityID { get; set; }

    [NotMapped]
    public ILocality Locality {
        get {
            return LocalityDB;
        }
        set {
            if (value is Locality)
                LocalityDB = (Locality)value;
        }
    }
    public virtual Locality LocalityDB { get; set; }
}

另外,请检查 LazyLoading 是否已打开。