gpt4 book ai didi

c# - Entity Framework 核心 3.1.7 : failure during Update of record

转载 作者:行者123 更新时间:2023-12-05 08:05:48 26 4
gpt4 key购买 nike

我有一个最简单的 ASP.NET Core 3.1 Web API 解决方案,其中一个模型项目使用 Entity Framework Core 3.1.7 将我的模型映射到 SQL Server。

我有以下实体:

[Table("SessionDetails")]
public class SessionDetailsModel
{
public long Id { get; set; }
public DateTime CreateDate { get; set; }
public Guid Token { get; set; }
public bool IsValid { get; set; }
}

每次用户调用登录端点 (POST) 时创建。

数据库上下文配置如下:

public class RunMeDbContext : DbContext
{
public RunMeDbContext(DbContextOptions<RunMeDbContext> options) : base(options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SessionDetailsModel>()
.HasKey(x => new {x.Id, x.CreateDate});

base.OnModelCreating(modelBuilder);
}

public DbSet<SessionDetailsModel> SessionDetails { get; set; }
}

插入成功,但是当我调用注销端点时,它通过 token 字段获取先前创建的 SessionDetails 记录,并尝试将“IsValid”字段(bool)从 true 更新为false,我得到以下异常:

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

我是唯一连接到数据库的人,在阅读并发冲突后,我可以保证没有对记录进行其他更改。

我的代码:

    public async Task<bool> InvalidateSession(Guid token)
{
var session = await _dbContext.SessionDetails.FirstOrDefaultAsync(sd => sd.Token.Equals(token))
.ConfigureAwait(false);

if (session == null)
return false;

session.IsValid = false;

_dbContext.Update(session);
await _dbContext.SaveChangesAsync().ConfigureAwait(false);

return true;
}

提示:在调试时我注意到虽然我正在更改的唯一字段是“IsValid = false”,但由于某些奇怪的原因,Token 字段也被修改了(尽管它的值是相同的):

正如您在此屏幕截图中所见: enter image description here

最佳答案

我无法重现此行为。看看您是否可以修改它以展示您正在观察的行为。

using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace EfCore3Test
{

[Table("SessionDetails")]
public class SessionDetailsModel
{
public long Id { get; set; }
public DateTime CreateDate { get; set; }
public Guid Token { get; set; }
public bool IsValid { get; set; }
}
public class Db : DbContext
{

public Db(): base()
{

}

private static readonly ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddFilter((category, level) =>
category == DbLoggerCategory.Database.Command.Name
&& level == LogLevel.Information).AddConsole();
});


protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var constr = "Server = localhost; database = efcore3test; integrated security = true";

optionsBuilder.UseLoggerFactory(loggerFactory)
.UseSqlServer(constr, o => o.UseRelationalNulls());

//optionsBuilder.UseLazyLoadingProxies();
base.OnConfiguring(optionsBuilder);
}

public DbSet<SessionDetailsModel> SessionDetails { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SessionDetailsModel>()
.HasKey(x => new { x.Id, x.CreateDate });

modelBuilder.Entity<SessionDetailsModel>().Property(e => e.Id).UseIdentityColumn();

modelBuilder.Entity<SessionDetailsModel>().HasIndex(e => e.Token).IsUnique(true);

base.OnModelCreating(modelBuilder);
}
}


class Program
{
static void Main(string[] args)
{

long id;
DateTime created = DateTime.Now;
Guid token = Guid.NewGuid();

using (var db = new Db())
{

db.Database.EnsureDeleted();
db.Database.EnsureCreated();

var s = new SessionDetailsModel();
s.CreateDate = created;
s.Token = token;
s.IsValid = true;
db.SessionDetails.Add(s);
db.SaveChanges();
id = s.Id;
}
using (var db = new Db())
{
var sd = db.SessionDetails.Where(d => d.Token == token).Single();
sd.IsValid = false;
db.SaveChanges();
}
}
}

}

关于c# - Entity Framework 核心 3.1.7 : failure during Update of record,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63457449/

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