【发布时间】:2011-05-26 19:44:40
【问题描述】:
我正在尝试建立多对一的关系。表示“许多”的实体具有指向父实体的导航属性。它看起来像这样:
public abstract class BaseEntity
{
/// <summary>
/// Key Field for all entities
/// </summary>
///
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
/// <summary>
/// Date entity was created
/// </summary>
public DateTime DateCreated { get; set; }
/// <summary>
/// Last date Modified
/// </summary>
public DateTime DateModified { get; set; }
/// <summary>
/// keep track of Row Version used for concurrency
/// </summary>
[Timestamp]
public Byte[] RowVersion { get; set; }
}
public abstract class Document : BaseEntity
{
#region Primitive Properties
/// <summary>
/// Boolean value to determine if Document is in an active state
/// </summary>
public bool IsActive { get; set; }
/// <summary>
/// Document comments and information
/// </summary>
[Required]
public string Description { get; set; }
#endregion
#region Navigation Properties
public ICollection<Comment> Comments { get; set; }
/// <summary>
/// FK back to User who owns document
/// </summary>
//public Guid OwnerId { get; set; }
public Guid OwnerId { get; set; }
/// <summary>
/// Navigation Back to User who owns document
/// </summary>
public User Owner { get; set; }
#endregion
}
public class Project : BaseEntity
{
public string Name { get; set; }
public string ProjectNumber { get; set; }
public string Description { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public string Currency { get; set; }
#region Navigation Properties
public virtual Address Address { get; set; }
public virtual CompanyCode CompanyCode { get; set; }
public virtual ICollection<Contact> TeamMembers { get; set; }
#endregion
}
public class Rfi : Document
{
public string Number { get; set; }
#region Navigation Properties
//This points back to a Project Entity
public virtual Guid ProjectId { get; set; }
public virtual Project Project { get; set; }
#endregion
}
因此,当我插入上述实体时,我将 ProjectId 从应用程序传递到 Rfi 实体(而不是整个 Project 实体)。一切都很好。我遇到的问题是,当我将 Rfi 对象从数据库中拉出时,正在填充 ProjectId,但 Project 实体为空。我默认使用延迟加载。我是否也需要在 Project 实体上指定导航属性?我真的不想。除非,我可以在我的 Rfi 上执行映射来完成此操作。
更新: 我假设 EF 4.1 会为我加载我的对象,但似乎有时我需要明确地包含我想要加载的对象。我不完全确定为什么。我正在使用存储库来查询我的实体。下面是我用来查询 Rfi 对象的方法:
public IQueryable<TEntity> GetQuery(Expression<Func<TEntity, bool>> predicate)
{
return _context.Set<TEntity>().AsQueryable();
}
我最终做了什么,在我的服务层我这样称呼它:
public Rfi FindByNumber(string number)
{
var rfi = rfiRepository.GetQuery(r => r.Number == number).Include(r => r.Project).Single;
return rfi
}
【问题讨论】:
-
Project和Document类的外观如何?您不一定需要另一侧的导航属性。你所描述的应该正常工作。问题可能隐藏在其他类或任何其他映射中。 -
我更新了代码示例。 Document 派生自 BaseEntity 类型。
-
您使用的是 SQL Server 吗?我认为
DatabaseGeneratedOption.Identity不适用于SQL Server 中的Guid(尽管模型允许此设置,但它不是数据库中的标识)。但这可能不是您的问题的原因。使用Include的Project属性进行预加载是否有效? -
我正在使用 SQL 服务器,它可以工作。
-
对不起,你是对的,这是 EF 1 中的限制。从 EF 4 开始它可以工作。
标签: c# ef-code-first entity-framework-4.1 entity-relationship navigation-properties