以下是我尝试使用热切的加载集合返回的实体示例.
混音 - >曲目(收藏) - >标签(收藏)
我需要返回一个带有急切加载的曲目和标签的混音的分页列表,而不需要通过使用Future <>()函数为曲目+标签运行多个查询来进行相对简单的分页.
因为需要对这些数据进行分页...如何恢复所有数据,以便NHibernate在显示数据时不会出现N + 1问题.
保罗
请在继续说"查询查询中的提取类型"之前阅读.那不是我追求的.
我正在寻找一种方法来急切加载一个完整的对象图(对象+所有子对象及其所有子对象等).
我不希望枚举要加载的所有属性.直到运行时我才知道它们.
N + 1个查询不是问题.但是在这个神奇的操作结束时,我不想在我的图表中留下单个代理或惰性集合.
应该可以编写一些反射和递归查看所有属性的代码.但是收藏会使这种尴尬和复杂.
有些人推荐Dozer这种东西,但这似乎有点过分,所以我想把它作为最后的手段保存.
我有这个存储库,
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly DbContext context;
private readonly DbSet<TEntity> dbEntitySet;
public Repository(DbContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
this.dbEntitySet = context.Set<TEntity>();
}
public IEnumerable<TEntity> GetAll()
{
return this.dbEntitySet;
}
public IEnumerable<TEntity> GetAll(string include)
{
return this.dbEntitySet.Include(include);
}
public IEnumerable<TEntity> GetAll(string[] includes)
{
foreach (var include in includes)
this.dbEntitySet.Include(include);
return this.dbEntitySet;
}
public void Create(TEntity model)
{
this.dbEntitySet.Add(model);
}
public void Update(TEntity model)
{
this.context.Entry<TEntity>(model).State = …Run Code Online (Sandbox Code Playgroud) 我正在使用public_activity和我的一个部分我有这个电话:
<%= link_to "#{activity.trackable.user.name} " + "commented on " + "#{activity.trackable.node.name}", node_path(activity.trackable.node.family_tree_id,activity.trackable.node) %>
Run Code Online (Sandbox Code Playgroud)
这是通过这个电话执行的:
<% @unread_act.each do |friend| %>
<li><%= render_activity friend %> </li>
<% end %>
Run Code Online (Sandbox Code Playgroud)
那个实例变量在我ApplicationController这里分配:
before_filter :handle_nofications
def handle_nofications
if current_user.present?
@unread_act = Notification.where(owner_id: current_user).includes(:trackable => :user).unread_by(current_user)
end
end
Run Code Online (Sandbox Code Playgroud)
我正在使用gem bullet,找到N + 1个查询,我得到的反馈是这样的:
N+1 Query detected
Comment => [:node]
Add to your finder: :include => [:node]
N+1 Query method call stack
Run Code Online (Sandbox Code Playgroud)
我最初得到了该消息:trackable,并为:user.这两个我现在都渴望通过includes该赋值语句加载.
但是,我不知道如何在热切的加载中达到3级 - 而不仅仅是两级.
鉴于节点被调用activity.trackable.node.name …
ruby-on-rails query-optimization eager-loading ruby-on-rails-4 public-activity
我在理解延迟加载的工作方式时遇到了麻烦。例如,在下面的例子中,我可以访问Courses的Students内Where()子句:
context.Students
.Where(st=>st.Courses
.Select(c=>c.CourseName).Contains('Math')
).ToList();
Run Code Online (Sandbox Code Playgroud)
但是,尽管我没有禁用延迟加载,但null如果不使用以下内容,则将引发异常Include():
context.Students.Single(s => s.StudentId == 1)
.Courses.ToList()
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下为什么会这样吗?
我在config/application.rb中遵循了注释指南
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
Run Code Online (Sandbox Code Playgroud)
但是当我加入Rails.application.config.eager_load_paths << Rails.root.join('lib')时config/initializers/eager_load.rb.
它抛出 <top (required)>': can't modify frozen Array (RuntimeError)
是的,如果我把它放在里面它是有效的config/application.rb.
我想知道为什么它不能用于初始化器以及如何使用约定使其工作?
我花了两天的时间来反对这个问题,我似乎无法破解它(问题是).相同的代码工作正常,直到我添加数据库关系,我已经读了很多关于延迟加载.
我有两个数据库表,它们之间有1:1的关系. PromoCode表跟踪代码,并有一个名为的PK列id. CustomerPromotable有一个PromoId链接到PromoCode表的列id.这两个表没有其他关系.我在SQL Server Management Studio中生成了所有这些,然后从数据库生成模型.
为了使问题稍微复杂一点,我在WCF数据服务中这样做,但我不认为这应该有所作为(它在添加数据库关系之前有效).启用日志记录后,我总是在日志文件中获得带有文本的异常:
Dispose后访问DataContext.
我的函数当前返回表中的所有条目:
using (MsSqlDataContext db = new MsSqlDataContext())
{
// This causes issues with lazy-loading
return db.PromoCodes.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
我已经阅读了很多文章/页面/答案,他们都说要使用这种.Include()方法.但这对我不起作用:
return db.PromoCodes.Include(x => x.CustomerPromos).ToArray();
Run Code Online (Sandbox Code Playgroud)
我也尝试了"魔术字符串"版本:
return db.PromoCodes.Include("CustomerPromos").ToArray();
Run Code Online (Sandbox Code Playgroud)
我设法开始工作的唯一代码是:
PromoCode[] toReturn = db.PromoCodes.ToArray();
foreach (var p in toReturn)
p.CustomerPromos.Load();
return toReturn;
Run Code Online (Sandbox Code Playgroud)
我已经尝试.Where()为查询添加了一个条件,我已经尝试过了.Select(),我尝试.Include()过后移动.Where()(这个答案说要做到最后,但我认为这仅仅是由于嵌套查询).我已经读过有关.Include() 静默失败的场景,毕竟我不会更接近.
我错过了什么?语法问题?逻辑问题?一旦我将这个"简单"的案例工作,我还需要嵌套Includes(即如果CustomerPromo表有关系 …
我有一个与Section模型相关的Post模型,这取决于工作的额外条件:
<?php
class Post extends Base
{
public function section()
{
return $this->belongsTo('App\Models\Section', 'id_cat')->where('website', $this->website);
}
}
Run Code Online (Sandbox Code Playgroud)
当我想检索帖子并获取它的关联部分时,可以按照以下方式进行操作:
$post = Post::first();
echo $post->section->name; // Output the section's name
Run Code Online (Sandbox Code Playgroud)
但是,当尝试使用急切的负载获取该部分时:
Post::with(['section'])->chunk(1000, function ($posts) {
echo $post->section->name;
});
Run Code Online (Sandbox Code Playgroud)
Laravel抛出以下异常:
PHP error: Trying to get property of non-object
Run Code Online (Sandbox Code Playgroud)
当我对上述热切的加载查询返回的Post对象进行调试时,我注意到该section关系为null。请注意,如果我从belongsTo关联中删除条件,则它工作正常。
你们有什么想法为什么会发生吗?
我有这样的控制器功能
public function show(NovelRequest $request, Novel $novel)
{
// load the chapters
$novel->chapters;
// return the detail view of a novel
return view('novels.show', compact('novel'));
}
Run Code Online (Sandbox Code Playgroud)
我收到一个新的对象,因为我使用路由模型绑定.但是,我想加载的不仅仅是章节.因为如果我现在做类似的事情会引起很多请求
$novel->chapters;
$novel->bookmarks;
...
Run Code Online (Sandbox Code Playgroud)
当我已经拥有这个小说的对象时,我想知道是否有一种加载"多重"关系的方法.通常我会喜欢
Novel::with('chapters', 'bookmarks')-> ...
Run Code Online (Sandbox Code Playgroud)
但是,我已经有了这个新颖的物体,所以我不想第二次看.
您如何编写一个渴望递归加载某个角色的父母和孩子的模型。因此,不仅是您现在要担任的角色的孩子,而且还是孩子。
您是否冒着无限循环结束的风险,还是SQLAlchemy具有检测这些逻辑的逻辑?
SQLAlchemy模型如下:
from sqlalchemy.ext.declarative import declarative_base
roles_parents = Table(
'roles_parents', Base.metadata,
Column('role_id', Integer, ForeignKey('roles.id')),
Column('parent_id', Integer, ForeignKey('roles.id'))
)
Base = declarative_base()
class Role(Base):
__tablename__ = 'roles'
id = Column(Integer, primary_key=True)
name = Column(String(20))
parents = relationship(
'Role',
secondary=roles_parents,
primaryjoin=(id == roles_parents.c.role_id),
secondaryjoin=(id == roles_parents.c.parent_id),
backref=backref('children', lazy='joined'),
lazy='joined'
)
def get_children(self):
logger.log_dbg("get_children(self) with name: " + self.name)
for child in self.children:
yield child
for grandchild in child.get_children():
yield grandchild
@staticmethod
def get_by_name(name):
logger.log_dbg("get_by_name( " + name + " )")
with …Run Code Online (Sandbox Code Playgroud) eager-loading ×10
c# ×3
lazy-loading ×3
laravel ×2
belongs-to ×1
eloquent ×1
hibernate ×1
java ×1
linq ×1
many-to-many ×1
nhibernate ×1
pagination ×1
python ×1
sqlalchemy ×1