我正在try 从数据库更新现有的业务合作伙伴,但失败了
"Microsoft. EntityFrame Core. GbUpdateConcurrencyResponse"
我补充道:
[Timestamp]
public byte[] Version { get; set; } // optimistic concurrency
我写下了相关代码:
DBCOontext:
public class DbTestingCSharp : DbContext
{
public DbSet<BusinessPartner> BusinessPartners { get; set; }
public DbSet<BPLayerXScraper> BPLayerXScrapers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=...;Database=...;...;MultipleActiveResultSets=True");
}
public DbTestingCSharp()
{
}
// DI? Auf jeden Fall in Controller
public DbTestingCSharp(DbContextOptions<DbTestingCSharp> options) : base(options)
{
}
}
数据 struct
public class BusinessPartner
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
private string _name = String.Empty;
[Required, MaxLength(200)]
public string Name
{
get { return _name; }
set { _name = value.Length > 200 ? value.Substring(0, 200) : value; }
}
public EProductLifeCycleTyp EProductLifeCycle { get; set; } = EProductLifeCycleTyp.None;
public ESource ESource { get; set; }
public EBusinessPartner EBusinessPartner { get; set; }
public string BusinessScope { get; set; } = String.Empty;
public string CommercialRegisterNumber { get; set; } = String.Empty;
public string Description { get; set; } = String.Empty;
public string Website { get; set; } = String.Empty;
public virtual List<BPLayerXScraper> BPLayerXScrapers { get; set; } = new List<BPLayerXScraper>();
[Required]
public DateTime TimeStampCreated { get; set; } = DateTime.UtcNow;
public DateTime? TimeStampUpdated { get; set; }
[Timestamp]
public byte[] Version { get; set; } // optimistic concurrency
}
public class BPLayerXScraper
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
//Hash-value, if something changed? Naja, kann ich ja machen schadet ja nicht
public string Hash { get; set; }
public int LinksOnTheLandingPage { get; set; }
public string Heading { get; set; }
public string Text { get; set; }
public string URL { get; set; }
public int Layer { get; set; }
[NotMapped]
public List<string> Links { get; set; } = new List<string>();
[Required]
public DateTime TimeStampCreated { get; set; } = DateTime.UtcNow;
public DateTime? TimeStampUpdated { get; set; }
public BPLayerXScraper()
{
}
public BPLayerXScraper(string websiteUrl)
{
URL = websiteUrl;
}
}
try 更新现有对象:
try
{
var businessPartner = dbTarget.BusinessPartners
.Include(bp => bp.BPLayerXScrapers)
.FirstOrDefault(bp => bp.Name == name);
if (businessPartner == null)
{
throw new KeyNotFoundException("BusinessPartner not found.");
}
if (businessPartner == null)
{
Console.WriteLine("BusinessPartner not found.");
return; // Or handle the absence of BusinessPartner accordingly
}
BPLayerXScraper newScraper = new BPLayerXScraper
{
Hash = "abc123",
LinksOnTheLandingPage = 10,
Heading = "Fantasy Heading",
Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
URL = "https://example.com",
Layer = 3,
Links = new List<string> { "https://example.com/link1", "https://example.com/link2" },
TimeStampCreated = DateTime.UtcNow,
TimeStampUpdated = DateTime.UtcNow.AddDays(1)
};
// Adding the new scraper to the BusinessPartner's collection of scrapers
businessPartner.BPLayerXScrapers.Add(newScraper);
// Saving changes in the database
dbTarget.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
Console.WriteLine("A concurrency conflict occurred. Handling...");
// Handling concurrency exception specifically for updates to BPLayerXScrapers or BusinessPartner
foreach (var entry in ex.Entries)
{
var databaseValues = entry.GetDatabaseValues();
if (databaseValues != null)
{
entry.OriginalValues.SetValues(databaseValues);
}
else
{
// It hits here, even the object is presented in the database
Console.WriteLine("The object was deleted from the database.");
}
}
dbTarget.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine($"An error occurred: {e.Message}");
}
它失败了:
Microsoft. EntityFrame Core. GbUpdatateConcurrency异常:' 数据库操作预计会影响1行,但实际上 受影响的0行;数据可能已被修改或删除 实体已加载.看到 https://go.microsoft.com/fwlink/?LinkId=527962获取有关信息 理解和处理乐观并发异常.'
记录 :
dbug:20.04.2024 09:29:06.184核心事件ID.SaveChanges启动[https://go.microsoft.com/fwlink/?LinkId=52796204](Microsoft.EntityFrameworkCore.Update)
Sensitive 记录 :
DBug:20.04.2024 09:36:45.145 CoreEventId.SaveChangesStarting[https://go.microsoft.com/fwlink/?LinkId=52796204](Microsoft.EntiyFrameworkCore.Update) 开始为‘DbTestingCSharp’保存更改. (Microsoft.EntityFrameworkCore.ChangeTracking):20.04.2024 09:36:45.148核心事件ID.检测更改正在启动[20.04.2024]dbug 正在启动‘DbTestingCSharp’的DetectChanges. (Microsoft.EntityFrameworkCore.ChangeTracking):20.04.2024 09:36:45.165核心事件ID.收集更改检测到[20.04.2024]dBug 已添加1个实体,并从密钥为‘{ID:f7e9aec7-c04c-41e2-aad1-b1283536c32e}’的实体上的导航‘BusinessPartner.BPLayerXSCrapers’中删除了0个实体. (Microsoft.EntityFrameworkCore.ChangeTracking):20.04.2024 09:36:45.192核心事件ID.外来密钥更改检测到[20.04.2024]dbug 检测到密钥为‘{ID:ab313081-5c02-4e60-98b2-bc651ba737fd}’的实体的外键属性‘BPLayerXSCraper.BusinessPartnerId’已从‘(NULL)’更改为‘f7e9aec7-c04c-41e2-aad1-b1283536c32e’. (Microsoft.EntityFrameworkCore.ChangeTracking):20.04.2024 09:36:45.198核心事件ID.已启动跟踪[20.04.2024]DBug 上下文‘DbTestingCSharp’已开始跟踪密钥为‘{ID:ab313081-5c02-4e60-98b2-bc651ba737fd}’的‘BPLayerXSCraper’实体. (Microsoft.EntityFrameworkCore.ChangeTracking):20.04.2024 09:36:45.200核心事件ID.检测更改已完成[10801]dBug ‘DbTestingCSharp’的DetectChanges已完成. (Microsoft.EntityFrameworkCore.Database.Connection):20.04.2024 09:36:45.236关系事件ID.连接打开[20000]dBug 正在打开与服务器‘xxxx’上的数据库‘xTesting’的连接. (Microsoft.EntityFrameworkCore.Database.Connection):20.04.2024 09:36:45.239关系事件ID.连接打开[20.04.2024]dBug 已打开与服务器‘xxxx’上的数据库‘xTesting’的连接. (Microsoft.EntityFrameworkCore.Database.Command):20.04.2024 09:36:45.241关系事件ID.命令创建[20.04.2024]dBug 正在为‘ExecuteReader’创建DbCommand. (Microsoft.EntityFrameworkCore.Database.Command):20.04.2024 09:36:45.242关系事件ID.命令创建[20.04.2024]dBug 已创建‘ExecuteReader’的DbCommand(%1ms). (Microsoft.EntityFrameworkCore.Database.Command):20.04.2024 09:36:45.244关系事件Id.CommandInitialized[20.04.2024]DBug 已初始化‘ExecuteReader’的DbCommand(%3ms). (Microsoft.EntityFrameworkCore.Database.Command):20.04.2024 09:36:45.247关系事件ID.命令执行[20.04.2024]dBug 正在执行数据库命令[Parameters=[@p9=‘ab313081-5c02-4e60-98b2-bc651ba737fd’,@p0=‘f7e9aec7-c04c-41e2-aad1-b1283536c32e’(可为空),@p1=‘abc123’(可为空)(大小=4,000),@p2=‘幻想标题’(可为空)(可为假)(大小=4,000),@p3=‘3’,@p4=‘10’,@p5=‘Lorem ipsum or Site amet,consecteur adipiscing elit’(可为空)(大小=4,000),@p6=‘2024-04-20T07:36:31.9677616Z’,@p7=‘2024-04-21T07:36:31.9677827Z’(可为空=真),@p8=‘https://example.com’(可为空=假)(大小=4,000)],命令类型=‘文本’,命令超时=‘30’] 设置IMPLICIT_TRANSACTIONS OFF; 将NOCOUNT设置为ON; UPDATE[BPLayerXSCrapers]set[BusinessPartnerId]=@p0,[Hash]=@p1,[Heading]=@p2,[Layer]=@p3,[LinksOnTheLandingPage]=@p4,[Text]=@p5,[TimeStampCreated]=@p6,[TimeStampUpdate]=@p7,[URL]=@p8 输出1 其中[ID]=@p9; 信息:20.04.2024 09:36:45.256 RelationalEventId.CommandExecuted[20101](Microsoft.EntityFrameworkCore.Database.Command) 已执行数据库命令(10ms)[Parameters=[@p9=‘ab313081-5c02-4e60-98b2-bc651ba737fd’,@p0=‘f7e9aec7-c04c-41e2-aad1-b1283536c32e’(可为空),@p1=‘abc123’(可为空=假)(大小=4,000),@p2=‘幻想标题’(可为空)(可为假)(大小=4,000),@p3=‘3’,@p4=‘10’,@p5=‘Lorem ipsum dolor Site amet,consecteur adipiscing elit’(可为空)(大小=4,000)@p6=‘2024-04-20T07:36:31.9677616Z’,@p7=‘2024-04-21T07:36:31.9677827Z’(可为空=真),@p8=‘https://example.com’(可为空=假)(大小=4,000)],命令类型=‘文本’,命令超时=‘30’] 设置IMPLICIT_TRANSACTIONS OFF; 将NOCOUNT设置为ON; UPDATE[BPLayerXSCrapers]set[BusinessPartnerId]=@p0,[Hash]=@p1,[Heading]=@p2,[Layer]=@p3,[LinksOnTheLandingPage]=@p4,[Text]=@p5,[TimeStampCreated]=@p6,[TimeStampUpdate]=@p7,[URL]=@p8 输出1 其中[ID]=@p9; DBug:20.04.2024 09:36:45.263 CoreEventId.OptimisticConcurrencyException[https://go.microsoft.com/fwlink/?LinkId=52796206](Microsoft.EntiyFrameworkCore.Update) Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException:数据库操作预计影响1行(S),但实际影响0行(S);自加载实体以来,数据可能已被修改或删除.有关了解和处理乐观并发异常的信息,请参见https://go.microsoft.com/fwlink/?LinkId=527962. (Microsoft.EntityFrameworkCore.Database.Command):20.04.2024 09:36:45.266 RelationalEventId.DataReader关闭[20301]dBug 正在将数据读取器关闭到服务器‘xxxx’上的‘xTesting’. (Microsoft.EntityFrameworkCore.Database.Command):20.04.2024 09:36:45.268 RelationalEventId.DataReader正在部署[20300]dBug 在花费9毫秒读取结果后,服务器‘xxxx’上的‘xTesting’数据读取器正在被释放. (Microsoft.EntityFrameworkCore.Database.Connection):20.04.2024 09:36:45.270关系事件ID.连接关闭[20.04.2024]DBug 正在关闭与服务器‘xxxx’上的数据库‘xTesting’的连接. (Microsoft.EntityFrameworkCore.Database.Connection):20.04.2024 09:36:45.271关系事件ID.连接关闭[20.04.2024]dBug 已关闭与服务器‘xxxx’上的数据库‘xTesting’的连接(%1ms). 引发异常:Microsoft.EntiyFrameworkCore.dll中的‘Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException’
我应该改变什么,如何改变?