gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:33:25 24 4
gpt4 key购买 nike

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

我在 Controller 中有一个 Action

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,...

Controller 会将这些参数传递给 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; }
}

最佳答案

我同意史诗先生的观点,我认为从 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;

关于c# - 如何传递参数以包含在 URL 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33958674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com