简体   繁体   English

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

[英]How to pass the parameters to include in URL?

In the repository class of WebApi project there is the method GetSingleIncluding() that returns an entity with indluded objects that were passed as parameters.在 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();
}

I have an action in a controller我在控制器中有一个动作

public HttpResponseMessage GetFull(int id, string entities)

I use it as:我用它作为:

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

here I pass explicitly a parameter x => x.Persons这里我明确地传递了一个参数x => x.Persons

Is there any way to pass this parameters by url request?有没有办法通过url请求传递这个参数? Eg I will pass all objects (that can be include for the current entity) as string in the url例如,我会将所有对象(可以包含在当前实体中)作为 url 中的字符串传递

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

and the controller will be pass these params to the GetSingleIncluding() method:控制器会将这些参数传递给GetSingleIncluding()方法:

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

House entity房屋实体

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

I Agree with Mister Epic, I think it is not a good idea getting the "includes" from the url.我同意 Epic 先生的观点,我认为从 url 获取“包含”不是一个好主意。 Any way, you can pass to your method an array of strings:无论如何,您都可以将一个字符串数组传递给您的方法:

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

You need to add this "using":您需要添加此“使用”:

using System.Data.Entity;

You should have a look at odata.It has build in capabilities for adding includes.您应该看看 odata。它具有用于添加包含的内置功能。 Take a look at this link and read about the $expand parameter.查看此链接并阅读有关 $expand 参数的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM