.NET C#:如何删除外键属性



我的模型称为 station servicelevel station 包含一个称为servicelevelid的外键,该密钥指的是 servicelevel 表中的主键。

,但我无法显示为电视台的一部分的Servicelevel属性。

我可以在视图中通过书面形式显示站点:

 @Html.DisplayFor(model => model.Name)

,但是如果我写的话,它不会显示外国对象属性:

@Html.DisplayFor(model => model.ServiceLevel.Title)

 

如果有人可以解释为什么它不起作用,我真的很感激。

 

.cs和 servicelevel .cs:

public class Station
{
    public int StationId { get; set; }
    public int Number { get; set; }
    public string Name { get; set; }
    public int? ServiceLevelId { get; set; }
    [ForeignKey("ServiceLevelId")]
    public ServiceLevel ServiceLevel { get; set; }
}
public class ServiceLevel
{
    public int ServiceLevelId { get; set; }
    [Required]
    public string Title { get; set; }
}

圣诞快乐!

您的ServiceLevel属性不是虚拟的,因此EF懒惰加载无法正常工作。查询站点对象时,您必须使用Include()方法来阐明服务对象。这称为急切的加载。

context.Stations.Include(x=>x.ServiceLevel).ToList();

为了使其工作,您可以通过将'Virtual'关键字前缀前缀来制作Servicelevel Virtual。这将使您的POCO类代理人可以创建运行时间,以便在您打电话时可用;

public class Station
{
    public int StationId { get; set; }
    public int Number { get; set; }
    public string Name { get; set; }
    public int? ServiceLevelId { get; set; }
    [ForeignKey("ServiceLevelId")]
    public virtual ServiceLevel ServiceLevel { get; set; }
}

默认情况下,如果您不通过'Virtual'关键字将其前缀以使您的代码失败。

另一种方式,正如先前的答案所建议的那样,急切地将其加载,即迫使要加载的相关实体。以我的拙见,这不是最佳的方法,除了您有一些特定的理由。

最新更新