【问题标题】:How to pass the parameters to include in URL?如何传递参数以包含在 URL 中?
【发布时间】:2015-11-27 13:40:54
【问题描述】:

在 WebApi 项目的存储库类中有 GetSingleIncluding() 方法,它返回一个实体,其中包含作为参数传递的包含对象。

private readonly EFDbContext _context;
private IDbSet<T> _entities;            
private IDbSet<T> Entities
{
    get
    {
        _entities = _entities ?? _context.Set<T>();
        return _entities;
    }
}               
public T GetSingleIncluding(int id, params Expression<Func<T, object>>[] includeProperties)
{
    var query = Entities.Where(x => x.ID == id);

    foreach (var includeProperty in includeProperties)
    {
        query = query.Include(includeProperty);
    }

    return query.First();
}

我在控制器中有一个动作

public HttpResponseMessage GetFull(int id, string entities)

我把它用作:

var entitiy = Repository.GetSingleIncluding(id, x => x.Person);

这里我明确传递了一个参数x =&gt; x.Persons

有没有办法通过url请求传递这个参数?例如,我会将所有对象(可以包含在当前实体中)作为字符串传递给 url

http://localhost/api/House/1/Person,Address,...

控制器会将这些参数传递给GetSingleIncluding() 方法:

Repository.GetSingleIncluding(id, x => x.Person, y => y.Address);

房屋实体

public class House : BaseEntity
{
        public int PersonID { get; set; }
        public int HouseID { get; set; }
        public int AddressID { get; set; }
        ...
        public virtual Person Person { get; set; }        
        public virtual Address Address { get; set; }
 }

【问题讨论】:

  • 首先,我不相信这是可能的。您可以将原始值放入查询字符串中,但不能放入 Expression。您可能可以使用反射做一些疯狂的事情,但我必须质疑 Web 浏览器规定应该包含哪些 EF 导航属性的用例。你的 UI 应该不知道你的数据层。
  • 我不想将表达式放在查询字符串中。它应该只是一个字符串

标签: c# asp.net-mvc entity-framework asp.net-web-api


【解决方案1】:

我同意 Epic 先生的观点,我认为从 url 获取“包含”不是一个好主意。无论如何,您可以将字符串数组传递给您的方法:

public T GetSingleIncluding(int id, string[] includeProperties)
{
    var query = Entities.Where(x => x.ID == id);

    if (includeProperties != null && includeProperties.Count() > 0)
    {
        query = query.Include(includes.First());
        foreach (var include in includeProperties.Skip(1))
            query = query.Include(include);
    }

    return query.First();
}

你需要添加这个“使用”:

using System.Data.Entity;

【讨论】:

    【解决方案2】:

    您应该看看 odata。它具有添加包含的内置功能。看看这个link 并了解 $expand 参数。

    【讨论】:

    • 好的,谢谢。我知道它并在其他项目中使用。在这个项目中我不能使用 OData
    猜你喜欢
    • 1970-01-01
    • 2014-03-25
    • 2018-07-05
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多