EF 5 Codefirst:实例化复杂的导航属性

时间:2012-09-03 20:22:13

标签: entity-framework repository-pattern entity-framework-5

类Entry的属性Content应该总是有一个实例。

问题是,如果我在Entry构造函数中创建一个新的Content实例,当实体从数据库加载时,EF不会从数据库加载值,因为Content!= null(我嘲笑!),我应该在将Content保存到数据库之前检查Content == null是否存在?(更优雅的解决方案)?

我的代码:

public class Entry : ContentEntityBase
{
    public Entry()
    {
        this.Tags = new List<Tag>();
        //this.Content = new Content(); <==== My problem
    }
}

public class Content : EntityBase
{
    public Content()
    {
        this.ContentVersions = new List<ContentVersion>();
    }

    public virtual ICollection<ContentVersion> ContentVersions { get; set; }
}

public abstract class ContentEntityBase :  EntityBase
{
    public Guid ContentId { get; set; }
    public virtual Content Content { get; set; }
}

public abstract class EntityBase
{
    public EntityBase()
    {
        this.Id = Guid.NewGuid();
    }
}

0 个答案:

没有答案