小编sim*_*ada的帖子

单元测试时HttpContext.Current为null

我有以下web Api控制器方法.

当我通过网络运行此代码时,HttpContext.Current是,never null并给出所需的价值.

public override void Post([FromBody]TestDTO model)
{

    var request = HttpContext.Current.Request;
    var testName = request.Headers.GetValues("OS Type")[0];
    // more code

}
Run Code Online (Sandbox Code Playgroud)

但是,当我调用此方法时Unit Test,HttpContext.Current is always null.

我如何解决它?

c# unit-testing asp.net-web-api

7
推荐指数
2
解决办法
6728
查看次数

无法在 VS 2017 中安装“Microsoft.EntityFrameworkCore”

我在用VS Professional 2017 Version 15.2 (26430.16) Release

我正在尝试安装Microsoft.EntityFrameworkCore

Install-Package Microsoft.EntityFrameworkCore -Version 1.1.2
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

严重性代码说明项目文件行抑制状态错误无法安装包“Microsoft.EntityFrameworkCore 1.1.2”。您正在尝试将此包安装到面向“.NETFramework,Version=v4.5”的项目中,但该包不包含任何与该框架兼容的程序集引用或内容文件。有关详细信息,请联系包作者。0

我用谷歌搜索但没有找到答案。

我有Microsoft.Net Framework Version 4.7.02046Visual Studio Professional 2017 Version 15.2 (26430.16) Release

visual-studio visual-studio-2017

5
推荐指数
1
解决办法
3万
查看次数

如何忽略 order by 子句中的“null”

orderby 时如何忽略 name 属性中的 Null

student.Students= student.student.OrderBy(s=> s.Name ?? null).ToList();
Run Code Online (Sandbox Code Playgroud)

上面的代码总是list of students having Name = null as 1st element在列表中返回并且student with name 'system' in the end.

我想要什么ignore/exclude null in orderby。然后ull should always come to end of the the list

linq

4
推荐指数
1
解决办法
2071
查看次数

同时将对象添加到具有属性的列表中

我有,

List<Items> itemDetails = new List<Item>();
itemDetails.Add(new Item { isNew = true, Description = "test description" });
Run Code Online (Sandbox Code Playgroud)

为什么我不能写上面的代码

List<Items> itemDetails = new List<Item>().Add(new Item { isNew = true, Description = "test description" });
Run Code Online (Sandbox Code Playgroud)

它给出了错误

Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<>
Run Code Online (Sandbox Code Playgroud)

c#

3
推荐指数
1
解决办法
123
查看次数

我如何检查属性是否在更新前实际更改

我正在使用 EF 5(不是 6)。我有一个低于类的对象,它在使用 EF 的数据库中。

public class Student
{
  public string Name { get; set; }
  public int Age { get; set; }
  public DateTime DOB { get; set;}
}
Run Code Online (Sandbox Code Playgroud)

稍后的,

我收到了对同一对象/记录进行更新的请求。

但是在进行更新调用之前,我想交叉比较属性是否实际更改,因为我可能会获得相同的更新记录,因此不想进行盲目更新。

 var student = _context.Students.select(x =>x.Name == "").first();
 student.name = "";
 student.age = "";
 student.DOB = "";
_context.Entry(student).State = EntityState.Modified;
_context.saveChanges();
Run Code Online (Sandbox Code Playgroud)

EF 是否为我提供了一些内置方法?

或者,我需要一个一个地交叉比较每个属性并决定?我可以有20个属性...

请问有什么想法吗?

c# entity-framework entity-framework-5

3
推荐指数
2
解决办法
9003
查看次数

Request.CreateResponse&lt;List&lt;string&gt;&gt;(HttpStatusCode.OK, messages) 的替代方案

我已经在我的邮件中发送了api controller如下回复(.Net Framework 4.5)

 public virtual async Task<HttpResponseMessage> Import(Guid Id)
 { 
    ////
    return Request.CreateResponse<List<string>>(HttpStatusCode.OK, messages);
 }
Run Code Online (Sandbox Code Playgroud)

.NET Core 2.0 中上述方案的替代方案是什么?

我找到了一种新方法HttpResponseMessage(HttpStatusCode.Ok),但没有接受/接受消息参数的 constructor 方法。HttpResponseMessageadditional

那么我现在有什么选择呢?

.net asp.net-core

3
推荐指数
1
解决办法
7107
查看次数

无法解析 ApplicationContext 类型的服务

我有我的ApplicationContext如下: -

您可以看到我正在从ChildContext(子类)派生 ApplicationContext,最终派生自“IdentityDbContext”。

public class ApplicationContext : ChildContext
{
    public ApplicationContext(DbContextOptions<ChildContext> options)
    : base(options)
    {
    }

    public DbSet<Class> Class { get; set; }
}


public  class ChildContext : IdentityDbContext<IfsUser>, IIFSContext
{
    public ChildContext(DbContextOptions<ChildContext> options)
    : base(options)
    {
    }

    public virtual DbSet<Student> Students { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

启动文件

services.AddDbContext<ApplicationContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("ApplicationDB")));
Run Code Online (Sandbox Code Playgroud)

当我尝试获取实例时

var context = services.GetRequiredService<ApplicationContext>();
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

尝试激活“ApplicationContext”时无法解析“Microsoft.EntityFrameworkCore.DbContextOptions`1[ChildContext]”类型的服务。

c# asp.net-core

2
推荐指数
1
解决办法
4564
查看次数

为什么我不能使用 [HttpPost] 而不是 [HttpPost("[action]")]?

我不明白为什么我需要使用[HttpPost("[action]")]而不是[HttpPost]

如果使用[HttpPost("[action]")],则来自角度客户端的请求会触发控制器操作。

// POST: api/LeaveRequests
[HttpPost("[action]")]
public async Task<IActionResult> PostLeaveRequest([FromBody] LeaveRequest leaveRequest)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    _context.LeaveRequests.Add(leaveRequest);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetLeaveRequest", new { id = leaveRequest.EmployeeNo }, leaveRequest);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我只放置[HttPost],那么来自角度客户端的请求不会命中控制器操作,而是命中具有路径的方法[HttpGet("{id}")]

我的MVC路线

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
Run Code Online (Sandbox Code Playgroud)

我的角度 http.post

return this.http.post(this._apiUrl, body, options)
    .map(res => res.json()) // ...and calling .json() on the …
Run Code Online (Sandbox Code Playgroud)

routes asp.net-core

2
推荐指数
1
解决办法
4427
查看次数

EF Core包含多个级别的问题

使用EF 6,我这样查询它并且工作得很好.

IQueryable<Student> query = _testHelper.buildQuerty(id, userId)
        .Include(x => x.Class)
        .Include(x => x.Subjects)
        .Include(x => x.Subjects.Select(y => y.Category));
Run Code Online (Sandbox Code Playgroud)

问题: 同样在EF Core 2.0中不起作用.

错误

发生System.ArgumentException HResult = 0x80070057 Message =属性表达式'Subjects => {from Subjects y in Subjects select [y] .Category}'无效.表达式应表示属性访问:'t => t.MyProperty'.有关包含相关数据的详细信息,请参阅http://go.microsoft.com/fwlink/?LinkID=746393.

打开链接,并像这样重构但它仍然无法正常工作并给出相同的错误.

List<Student> query = _testHelper.buildQuerty(id, userId)
        .Include(x => x.Class)
        .Include(x => x.Subjects)
        .ThenInclude(Subjects => Subjects.Select(y => y.Category)).tolist();
Run Code Online (Sandbox Code Playgroud)

问题出在哪儿?

c# entity-framework entity-framework-core asp.net-core

1
推荐指数
1
解决办法
321
查看次数

我如何使用 AspNetCore 抛出 HttpResponseException(NotFound)

我写的方法.Net 4.5 很简单。它要么returns Student entity or throw NOT FOUND exception.

我正在努力port it into .NET Core 2.0. 根据我的理解,.net core建议返回IActionResult,我可以简单地返回NotFound().

但是,我不确定如何抛出 not HttpResponseException (Not Found) 异常。

方法:

public Student Get(Guid id)
{
    Student student = _studentSvc.Get(id);
    if (student != null)
        return student;
    else
        throw new HttpResponseException(HttpStatusCode.NotFound);
}
Run Code Online (Sandbox Code Playgroud)

试图:

public Student Get(Guid id)
{
    Student student = _svc.Get(id);
    if (student != null)
        return student;
    else
        return NotFound();
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试跟随,那么这条线会return student抱怨不能隐式地将学生转换为...Mvc.IActionResult某些东西

public …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net-core

0
推荐指数
1
解决办法
4559
查看次数