实体框架继承的属性未填充

时间:2013-10-13 14:44:32

标签: c# .net entity-framework entity-framework-4 ef-code-first

我的应用程序中有一个继承基类属性的类,它也使用代码首先映射到表。

当我查看数据库时,所有内容都按预期工作,所有值都填充在我预期的位置,但我的应用程序崩溃了。

检查检索到的记录并将其作为模型传递给视图时,可以看到所有者和创建者字段为空,即使在数据库中的继承表上,我也可以看到ID中填充了有效的用户ID。为什么这些不会被映射?

This is the model adding correctly with values populated.

This is what my view is getting after doing a lookup for the same item id

BaseClass的

    public class SiteModel
{
    public SiteModel() { }
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public string EntityType { get; set; }

    public DateTime Created { get; set; }

    [ForeignKey("Creator")]
    public int CreatorID;
    public SiteAccount Creator { get; set; }

    [ForeignKey("Owner")]
    public int OwnerID;
    public SiteAccount Owner { get; set; }

    [ForeignKey("Parent")]
    public int? ParentID;
    public SiteModel Parent { get; set; }

    public List<SiteModel> Children { get; set; }

    public SiteModel(SiteAccount creator)
    {
        Creator = creator;
        Owner = creator;
        Created = DateTime.Now;
        EntityType = this.GetType().Name;
    }
}

子类

    [Table("BlogPost")]
public class BlogPost : SiteModel
{
    public BlogPost() { }
    public BlogPost(string title, string content, string description, string tags, BlogCategory category, BlogStatus status, SiteAccount creator) : base(creator)
    {
        Title = title;
        Content = content;
        Description = description;
        Tags = tags;
        Parent = category;
        Status = status;
    }

    [Required]
    public string Title { get; set; }
    [Required]
    public string Content { get; set; }

    public string Description { get; set; }
    [Required]
    public string Tags { get; set; }
    public BlogStatus Status { get; set; }
}

1 个答案:

答案 0 :(得分:1)

我发现了问题,链接属性上没有启用延迟加载,要启用此更改

public SiteAccount Creator { get; set; }

public virtual SiteAccount Creator { get; set; }

虚拟关键字启用了延迟加载,因此只要对象本身就会获取导航属性。