设想
public class Product : Entity, IAggregateRoot
{
public string Name { get; set; }
public string Dimension { get; set; }
public decimal Volume { get; set; }
public bool Featured { get; set; }
public Farm Farm { get; set; }
public int FarmId { get; set; }
/// <summary>
/// Sell Price
/// </summary>
public decimal BidPrice { get; set; }
public int QuantityAvaliable { get; set; }
public ICollection<Image> Images { get; set; }
public string Description { get; set; }
public Category Category { get; set; }
public int CategoryId { get; set; }
public DateTime Created { get; set; }
public DateTime? Modified { get; set; }
}
public class Category : Entity, IAggregateRoot
{
public string Title { get; set; }
public string CategoryImage { get; set; }
public Category Parent { get; set; }
public DateTime Created { get; set; }
public DateTime? Modified { get; set; }
}
关系设置
public class ProductMap : EntityTypeConfiguration<Product>
{
public ProductMap()
{
HasKey(x => x.Id);
Property(x => x.Created).HasColumnType("DateTime");
Property(x => x.Modified).HasColumnType("DateTime");
Property(x => x.BidPrice).HasColumnType("Decimal");
#region RELATIONSHIP
//BelongsTo
HasRequired(x => x.Farm);
HasRequired(x => x.Category);
HasMany(x => x.Images);
#endregion
}
所以我有这两个模型,我需要从Product模型中获取带有类别信息的数据
我已经检查了我的数据库,数据是一致的,产品记录具有类别记录的FK。
但是当我尝试使用EF6获取产品数据时,类别信息没有出现,我得到了一个空对象。
Because of = () =>
{
_product = _repository.Find(p => p.Id == 1, p => p.Category);
};
It should_not_be_bull = () =>
_product.Category.ShouldNotBeNull();
来自数据库的响应是对于Category为空。但记录在那里。
我以前工作正常。由于某些随机的魔术原因,它只是停止工作。
查找方法
public virtual TEntity Find(Expression<Func<TEntity, bool>> predicate = null, params Expression<Func<TEntity, object>>[] includes)
{
var set = CreateIncludedSet(includes);
return (predicate == null) ?
set.FirstOrDefault() :
set.FirstOrDefault(predicate);
}
CreateIncludeSet
private IDbSet<TEntity> CreateIncludedSet(IEnumerable<Expression<Func<TEntity, object>>> includes)
{
var set = CreateSet();
if (includes != null)
{
foreach (var include in includes)
{
set.Include(include);
}
}
return set;
}
CreateSet方法
private IDbSet<TEntity> CreateSet()
{
return Context.CreateSet<TEntity>();
}
我的DbContext实现在这里
所有项目也都在这里,以供进一步分析
任何帮助都是有价值的。
谢谢
您的代码中的问题在CreateIncludedSet方法的这一行中:
set.Include(include);
是的,您包括了数据,但没有更改设置。您应该将其更改为以下内容:
set = set.Include(include);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句