实体框架包含-返回NULL

时间:2018-11-22 16:55:39

标签: c# entity-framework entity-framework-6

我想通过一个DB调用(急切加载)用EF加载相关实体,为此,我尝试使用如下include语句。

var db = _DbContext;
     var r1 = await
                db.Request.Where(r => idList.Contains(r.RequestId))
                .Include(r => r.RequestedService)
                ...more include
                ...more include
                ...more include
                .ToListAsync();

当我使用include语句运行它时,我会得到一个返回null的单项,但是如果我不使用include来运行它,则会使实体返回。在上面的语句之后,如果我添加了以下条件以进行空检查,我将返回该实体。

if(r1.HasAny() && r1[0] == null)
{
    r1 =
    await
        db.Request.Where(r => idList.Contains(r.RequestId)).ToListAsync();
}

添加包含可以更改收益的原因可能是什么?我将导航属性设置为虚拟和公共。

添加实体

public class Request : BaseEntity
{
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long RequestId { get; set; }

        public virtual ICollection<RequestedService> RequestedService { get; set; }
}


public class RequestedService : BaseEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long RequestedServiceId { get; set; }
    [Required]
    public long RequestId { get; set; }
    public virtual Request Request { get; set; }
}
public class RequestDbContext : DbContextBase
{
    public object SyncObject = new object();

    public RequestDbContext()
    {
        Database.SetInitializer<RequestDbContext>(null);
    }

    public RequestDbContext(string connectionStringName) : base(string.Empty)
    {
        Database.SetInitializer<RequestDbContext>(null);
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        base.OnModelCreating(modelBuilder);
    }

    public virtual DbSet<Request> Request { get; set; }

    public virtual DbSet<RequestedService> RequestedService { get; set; }

    public class RequestDbContextInitializer : CreateDatabaseIfNotExists<RequestDbContext>
    {
        protected override void Seed(RequestDbContext context)
        {
            base.Seed(context);
        }
    }
}

0 个答案:

没有答案