【问题标题】:Entity Framework : Eager loading not working with string foreign key实体框架:急切加载不使用字符串外键
【发布时间】:2017-10-29 09:52:37
【问题描述】:

我在使用预加载加载子实体时遇到问题,预加载在项目中的其他任何地方都可以正常工作,但它不适用于任何字符串外键。我的模型是:

public class Listing : BaseAudit<int>
{
    public int? CommunityId { get; set; }
    public string LotId { get; set; }


    public Lot Lot { get; set; }
}

public class Lot : BaseAudit<string>
{
    public ICollection<Listing> Listings { get; set; }
}

public class BaseAudit<T> : BaseId<T>
{
    public BaseAudit()
    {
        CreatedDate = DateTime.Now;
    }

    public DateTime? CreatedDate { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? UpdatedDate { get; set; }
    public string UpdatedBy { get; set; }
}

public class BaseModel
{
    public BaseModel()
    {
        Active = true;
    }

    public bool Active { get; set; }
}

public class BaseId<T> : BaseModel
{
    public T Id { get; set; }
}

我正在尝试加载ListingLot 属性,我已经尝试过:

_db.Listings.Where(m => m.CommunityId == communityId && m.LotId != null).Include(a => a.Lot).ToList();

我已经通过使用断点检查它是否生成了正确的 SQL,但它总是返回所有 Lot 属性为空。我无法弄清楚我在这里做错了什么。

【问题讨论】:

  • 通常的嫌疑人:前导空格的差异,大小写。
  • @GertArnold 我也检查过,但如果是这种情况,那么生成的 SQL 将不会给出任何正确的结果。 SQL Generated 给出了预期的结果,但在.ToList() 之后,子实体为空。
  • 生成的 SQL 给出了预期的结果 t 足够有说服力。您应该检查 SQL 查询本身是否返回预期结果。
  • 您似乎试图在LotsListings 之间配置一对多的关系:每个Lot 有零个或多个Listings,每个Listing 恰好属于一个Lot。我是正确的,还是有不属于“列表”的“批次”?
  • @SyedFarjadZiaZaidi 您在使用 EF6 吗?

标签: c# entity-framework ef-code-first


【解决方案1】:

简答: Listings 应该是一个虚拟集合; LotId 永远不会为空,Include 应该紧跟在您的 DbSet 之后。而且您可能应该为您的继承策略建模

长答案 您似乎试图在LotsListings 之间配置一对多关系:每个Lot 都有零个或多个Listings,每个Listing 恰好属于一个Lot

对于适当的一对多,您应该声明您的列表虚拟集合

public virtual ICollection<Listing> Listings { get; set; }

由于一对多关系,没有Lot就没有Listing,因此Lot的主键LotId的外键永远不会为空。

所以你有一个可以为空的 int communityId(这是真的吗?还是 communityId 是一个 int?),并且你希望所有 Listings 具有相同的 Listing.CommunityId inclusive the one and onlyLotthisListing 值具有:

using System.Data.Entity;

List<Listing> result = dbContext.Listings
    .Include(listing => listing.Lot)
    .Where(listing => listing.communityId == communityId)
    .ToList();

如果这没有帮助,那么您使用继承可能会导致问题。关系数据库不知道继承的概念。您应该使用流式 API(或属性)告诉实体框架将哪种继承策略建模到表中。见Inheritance Strategies

最后我看到有些主键是 int,有些主键是字符串。这真的是故意的吗?有用吗?

【讨论】:

    【解决方案2】:

    EF6 不支持在相关实体上使用 IncludeWhere

    一种可能的解决方法:Entity Framework: Filtering Related Entity Collections

    从 Entity Framework 6 开始,没有办法过滤哪些相关的 使用 .Include() 时会加载实体。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-09
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      • 2012-09-10
      相关资源
      最近更新 更多