如何传递参数以包含在URL中?

时间:2015-11-27 13:40:54

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

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

2 个答案:

答案 0 :(得分:1)

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

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;

答案 1 :(得分:1)

你应该看看odata.It已经内置了添加包含的功能。看看这个link并阅读有关$ expand参数的内容。

相关问题