如果我有以下模型结构 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 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关系的DB表.但是在查询问题项列表时,QuestionItem.By属性(UserItem表的引用对象)为null.
通常这是通过在查询级别使用.Include方法来实现的,但我无法找到我应该在哪里做到这一点.
任何帮助表示赞赏.
Supreet
正如@JuneT所提到的,您需要从客户端发送$expand标头.原因是默认情况下,Entity Framework不会遍历对象图,因为这需要在数据库中进行连接,如果您不需要这样做,可能会对性能产生负面影响.我在this blog post中提到的另一种替代方法是在服务器端使用过滤器为您添加该标头.例如,使用以下属性:
[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(); }