如果我有以下模型结构
public class QuestionItem: EntityData
{
public string Content { get; set; }
public bool IsAnswered { get; set; }
public int NumberOfAnswers
{
//todo: make it computable
get;
set;
}
public UserItem By { get; set; }
public string ById { get; set; }
public string AtLocation { get; set; }
}
& 父实体为
public class UserItem:EntityData
{
public string UserName { get; set; }
public string Gender { get; set; }
public string BaseLocation { get; set; }
public int Age { get; set; }
public int Points { get; set; }
}
这确实会生成具有正确 FK 关系的数据库表。但是当查询问题项目列表时,QuestionItem.By 属性(UserItem 表的引用对象)为空。
一般来说,这是通过在查询级别使用 .include 方法来实现的,但我无法找到我应该在哪里执行此操作。
任何帮助表示赞赏。
Supreet
正如@JuneT 提到的,你需要发送一个$expand
来自客户端的标头。原因是默认情况下实体框架不会遍历对象图,因为这需要在数据库中进行联接,如果您不需要这样做,可能会对性能产生负面影响。
我在中提到的另一种选择这篇博文 http://blogs.msdn.com/b/azuremobile/archive/2014/04/14/creating-mongodb-backed-tables-in-azure-mobile-services-with-net-backend.aspx,就是在服务器端使用过滤器为您添加该标头。例如,使用以下属性:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
class ExpandPropertyAttribute : ActionFilterAttribute
{
string propertyName;
public ExpandPropertyAttribute(string propertyName)
{
this.propertyName = propertyName;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
var uriBuilder = new UriBuilder(actionContext.Request.RequestUri);
var queryParams = uriBuilder.Query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries).ToList();
int expandIndex = -1;
for (var i = 0; i < queryParams.Count; i++)
{
if (queryParams[i].StartsWith("$expand", StringComparison.Ordinal))
{
expandIndex = i;
break;
}
}
if (expandIndex < 0)
{
queryParams.Add("$expand=" + this.propertyName);
}
else
{
queryParams[expandIndex] = queryParams[expandIndex] + "," + propertyName;
}
uriBuilder.Query = string.Join("&", queryParams);
actionContext.Request.RequestUri = uriBuilder.Uri;
}
}
您可以装饰您的操作以强制相关实体的扩展。
[ExpandProperty("By")]
public IQueryable<QuestionItem> GetAll() {
return base.Query();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)