[英]Context is null in Data Access Layer when using n-tier architecture in Web API, Entity Framework
I'm trying to create a Web API. 我正在尝试创建一个Web API。 I'm using Entity Framework here, code first approach.
我在这里使用实体框架,代码优先方法。
This is a n-tier architecture. 这是n层架构。 Meaning, I have created multiple projects in a single solution as shown below.
意思是,我在一个解决方案中创建了多个项目,如下所示。
I have a controller method which is a get method. 我有一个控制器方法,这是一个get方法。 I will pass userid as the parameter.
我将通过userid作为参数。
[Route("api/[controller]")]
[ApiController]
public class BankController : ControllerBase
{
private readonly IBankApplicationDAL _bankAPI;
public BankController(IBankApplicationDAL bankAPI)
{
_bankAPI = bankAPI;
}
[HttpGet("{userId}")]
public IActionResult GetAccountDetailsId(int userId)
{
try
{
var values = _bankAPI.GetAccountDetailsId(userId);
return Ok(values);
}
catch
{
throw;
}
}
}
In the DAL layer, this is what I have: 在DAL层中,这就是我所拥有的:
using BankApplicationAPI.Model;
using BankApplicationAPI.Data;
using System;
using System.Linq;
namespace BankApplicationAPI.DAL
{
public class BankApplicationDAL : IBankApplicationDAL
{
DataContext context;
public AccountDetails GetAccountDetailsId(int userId)
{
try
{
var values = context.AccountDetails.FirstOrDefault(x => x.UserId == userId); // context is null here.
return values;
}
catch (Exception ex)
{
throw;
}
}
}
}
This is the DataContext
I have: 这是我拥有的
DataContext
:
namespace BankApplicationAPI.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<AccountDetails> AccountDetails { get; set; }
public DbSet<TransactionDetails> TransactionDetails { get; set; }
}
}
When I run this application, I get an exception saying context is null in DAL method (where I have put comment). 当我运行该应用程序时,出现一个异常,说明DAL方法(在其中已添加注释)的上下文为null。
How do I create an object for DataContext
? 如何为
DataContext
创建对象? Can anyone help me here? 有人能帮我一下吗? It's very important.
这很重要。 Thank you very much.
非常感谢你。
EDIT 编辑
Startup.cs Startup.cs
public void ConfigureServices(IServiceCollection services)
{
var connection = @"Server=.\sqlexpress;Database=AppDB;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<DataContext>(x => x.UseSqlServer(connection));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton<IBankApplicationDAL, BankApplicationDAL>();
}
you should use this changing: 您应该使用此更改:
public class BankApplicationDAL : IBankApplicationDAL
{
DataContext _context;
public BankApplicationDAL(DataContext context)
{
_context = context;
}
public AccountDetails GetAccountDetailsId(int userId)
{
try
{
var values = context.AccountDetails.FirstOrDefault(x => x.UserId == userId); // context is null here.
return values;
}
catch (Exception ex)
{
throw;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.