我正在寻找一种回滚实体更改的方法。我遇到了这个答案,它显示了如何设置实体状态,但我想知道如果我只是处理我的dbContext实例而不调用dbContext.SaveChanges()或操作实体状态会发生什么。
我为此编写的代码肯定有效,但是我是否会通过这种方式拒绝更改而使任何内容处于不稳定状态?
我正在使用实体框架,并且想要执行批量更新。加载每一行、更新这些行,然后将它们保存回数据库的效率太低了。
所以我更愿意使用DbContext.Database.ExecuteSqlCommand(). 但是,如何使用此方法来更新 ID 列表中包含的 ID 的所有行呢?
这是我到目前为止所拥有的。
IEnumerable<int> Ids;
DbContext.Database.ExecuteSqlCommand("UPDATE Messages SET Viewed = 1 WHERE Id IN (@list)", Ids);
Run Code Online (Sandbox Code Playgroud)
我意识到我可以使用正确的查询手动构建一个字符串,但我更愿意按照通常建议的方式传递参数。
有什么办法可以实现这一点吗?
我正在尝试将应用程序配置为使用我的类(派生自DbContext)ApplicationDbContext连接到我的数据库。我已经制作了配置文件appsetting.json:
"Data": {
"SportStoreProducts": {
"ConnectionStrings":"Server=(localdb)\\MSSQLLocalDB;Database=SportStore;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Run Code Online (Sandbox Code Playgroud)
我使用依赖注入通过 Startup 构造传递对象实现IConfiguration(即appsetting.json):
public class Startup
{
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration { get; }
}
Run Code Online (Sandbox Code Playgroud)
现在我想在ConfigureServices方法中使用这个配置文件Startup并使用扩展方法AddDbContext来注册我ApplicationDbContext使用SportStore我在配置文件中分配的SQL数据库():
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(***);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我应该将什么UseSqlServer作为参数 (***)传递给方法,以便它可以使用我提供的配置属性将上下文连接到 SQL Server 数据库?
我有一个 ASP.NET Core 2.1 站点,注册了几个 DbContext 和一些条件连接字符串。
出于调试目的,我想列出所有DbContext已注册的及其连接字符串,以确保一切都配置良好。
这只是一个“测试”功能,不用于任何其他用途,所以请不要回答“你不应该这样做”、“这是反模式”等。
我的项目是 .net core 2 base,我在 startup.cs 文件中设置了上下文和存储库
services.AddDbContext<DocumentContext>(options => options.UseSqlServer(connection));
services.AddSingleton<IAuthRepository, AuthRepository>();
Run Code Online (Sandbox Code Playgroud)
IAuthRepository 文件:
public interface IAuthRepository
{
int Login(LoginRequest model);
int Register(RegisterRequest model);
}
Run Code Online (Sandbox Code Playgroud)
AuthRepository 文件:
private readonly DocumentContext db;
public AuthRepository(DocumentContext context)
{
this.db = context;
}
...
Run Code Online (Sandbox Code Playgroud)
控制器:
private IAuthRepository AuthMethod { get; set; }
public AuthController(IAuthRepository authMethod)
{
this.AuthMethod = authMethod;
}
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
InvalidOperationException:无法使用来自单例“...IAuthRepository”的范围服务“...DocumentContext”。
我需要从这个类访问上下文,以便我可以从数据库中检查一些数据,但我不知道如何将它传输到下面的服务:
internal class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private Timer _timer;
public TimedHostedService(ILogger<TimedHostedService> logger) //context ?
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is starting.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(60));
return Task.CompletedTask;
}
private void DoWork(object state)
{
_logger.LogInformation("Atualização automática");
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
启动文件:
namespace Products
{
public …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 EF Core 运行 .NET Core Web 应用程序。为了测试存储库,我添加了一个MyDbContext继承 EFDbContext和 interface 的IMyDbContext。
public interface IMyDbContext
{
DbSet<MyModel> Models { get; set; }
}
public class MyDbContext : DbContext, IMyDbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
public virtual DbSet<MyModel> Models { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
上下文接口被注入到我的通用存储库中:
public class GenericRepository<TEntity> : IGenericRepository<TEntity>
{
private readonly IMyDbContext _context = null;
public GenericRepository(IMyDbContext context)
{
this._context = context;
}
}
Run Code Online (Sandbox Code Playgroud)
当我在 startup.cs 上使用此代码(不带接口)时:
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(...));
Run Code Online (Sandbox Code Playgroud)
我收到以下运行时错误: …
尝试将 SQLite 用于我的应用程序时,Dotnet Core Web API 抛出
DbContextOptionsBuilder' 不包含 'UseSqlite' 的定义并且没有可访问的扩展方法 'UseSqlite'
如何解决这个问题?
我试过使用.Microsoft.EntityFrameworkCore;
使用 Microsoft.EntityFrameworkCore;
将 DBContext 注入我的存储库时,该using语句应该如何显示?
例如:Startup.cs
services.AddDbContext<VisualDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
Run Code Online (Sandbox Code Playgroud)
VisualDbContext.cs
public partial class VisualDbContext : DbContext
{
public VisualDbContext(DbContextOptions<VisualDbContext> options) : base(options)
{}
public DbSet<Template> Template { get; set; }
public DbSet<Exercise> Exercise { get; set; }
public DbSet<Symbol> Symbol { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
存储库
public class TemplateRepository : ITemplateRepository
{
private readonly VisualDbContext _dbContext;
public TemplateRepository(VisualDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<KeyValuePair<char, string>>> GetTemplateAsync(int templateId)
{
using (_dbContext) //this seems wrong...
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud) 我创建了一个 .net Core 控制台应用程序,并添加了以下依赖项注入包:
Microsoft.Extensions.DependencyInjection
要注入 EF Core DbContext 服务,以下是该项目的代码片段:
static void Main(string[] args)
{
// Create service collection and configure our services
var services = ConfigureServices();
// Generate a provider
var serviceProvider = services.BuildServiceProvider();
// Kick off our actual code
serviceProvider.GetService<Startup>().Run();
}
public static IConfiguration LoadConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables();
return builder.Build();
}
private static IServiceCollection ConfigureServices()
{
IServiceCollection services = new ServiceCollection();
// Set …Run Code Online (Sandbox Code Playgroud) c# dependency-injection dbcontext entity-framework-core .net-core
dbcontext ×10
c# ×7
.net-core ×3
.net ×2
asp.net-core ×2
asp.net ×1
asp.net-mvc ×1
ef-core-3.1 ×1
rollback ×1
scope ×1
service ×1
sql-server ×1