如何传递要包含在URL中的参数

本文关键字:参数 URL 何传递 包含 | 更新日期: 2023-09-27 18:24:49

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

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 => x.Persons

有什么方法可以通过url请求传递这些参数吗?E.g我将把所有对象(可以包括在当前实体中)作为字符串传递到url 中

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

控制器将这些参数传递给CCD_ 3方法:

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; }
 }

如何传递要包含在URL中的参数

我同意Mister Epic的观点,我认为从url中获取"includes"不是一个好主意。无论如何,您都可以将字符串数组传递给您的方法:

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;

您应该了解一下odata。它具有用于添加include的内置功能。查看此链接并阅读有关$expand参数的信息。