.net - 检索新插入的项目时虚拟属性为 null

标签 .net entity-framework entity

我正在使用 EF4.x、Code First 和 CaSTLe Windsor 进行 DI。我的问题:检索新插入的实体时,某些虚拟属性返回 null。我对此很陌生,所以请原谅我对一切如何运作的无知。一个非常简单的例子是这样的:

public class Address
{
    public int AddressID { get; set; }
    public string Street { get; set; }
    public int ProvinceID { get; set; }
    public virtual Province { get; set; }
    etc....
}

public class Province
{
    public int ProvinceID { get; set; }
    public string Name { get; set; }
    public string Abbreviation { get; set; }
    public int DisplayOrder { get; set; }
    etc...
}

因此,在 SaveChanges() 之后,我可以看到在数据库中正确创建的记录,但在加载地址实体的后续页面请求中,ProvinceID 已正确设置,但虚拟省份为空。重建后就没有问题了。我究竟做错了什么? TIA

更多信息:

我在存储库和工作单元模式中使用 DbContext。我有一个抽象 EF RepositoryBase 类,其中包含所有常见的 CRUD 方法。以下是常见 GET 方法的示例:

  public T Get(params object[] keyValues)
  {
     return _dbSet.Find(keyValues);
  }

  public IQueryable<T> Get(Func<T, bool> filter)
  {
     return _dbSet.Where(filter).AsQueryable();
  }

  public IQueryable<T> GetAll()
  {
     return _dbSet.AsQueryable();
  }

_dbSet 设置如下:

_dbSet = ((DbContext)_context).Set<T>(); // _context is of IDbContext

也许这里有什么东西导致了这个奇怪的问题?

最佳答案

因此,在导航属性加载、延迟加载和显式加载方面,EF 实际上有 2 个选项。根据我的经验,显式加载要好得多,因为它更难导致重大性能问题。

我写了一篇关于导航属性的文章,您可以阅读 here

要使用显式导航属性加载,您可以使用 .Ininclude 语句来指定在每个查询中加载哪些属性。

当您使用延迟加载时,我相信您需要在上下文中虚拟装饰所有导航属性,并且当您调用属性上的 get 时会查询数据库。

关于.net - 检索新插入的项目时虚拟属性为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11926750/

相关文章:

.net - 检测 .NET Framework 3.5 SP1 依赖项 (cmp. 3.5 w/o SP1)

c# - OrderBy 的正确行为

c# - 无法更新实体中的外键

wcf - Entity Framework 4 POCO 的存储过程错误 - "The FunctionImport could not be found in the container"

.net - 为什么需要 Web 服务才能从 Silverlight 访问数据库?

c# - Unity 中 RegisterInstance 的后期绑定(bind)版本

c# - 匿名方法和委托(delegate)

entity-framework - 与ID上的.SingleOrDefault相比,DbSet.Find方法要慢得多

mysql - 数据库设计 - 来自 super /父实体的共享关联

java - 为什么实体bean被认为是贫乏的?