Код: Выделить всё
namespace Domain
{
public class ExternalAccount
{
public Guid Id { get; set; }
public string APIKey { get; set; }
}
}
Код: Выделить всё
using Microsoft.AspNetCore.Identity;
namespace Domain
{
public class AppUser : IdentityUser
{
public ICollection ExternalAccounts { get; set; } = new List();
}
}
Код: Выделить всё
using Domain;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Persistence
{
public class DataContext : IdentityDbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DbSet ExternalAccounts { get; set; }
}
}
Код: Выделить всё
var user = await _context.Users.Include(p => p.ExternalAccounts).FirstOrDefaultAsync(x => x.UserName == "Bob");
if (user == null) return null;
ExternalAccount account = new ExternalAccount
{
Id = Guid.Parse("08186b29-e603-4cc8-9575-47b237775274"),
APIKey = "some long text here",
};
user.ExternalAccounts.Add(account);
var result = await _context.SaveChangesAsync() > 0;
Код: Выделить всё
"statusCode": 500,
"message": "The database operation was 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.",

Есть идеи, в чем может быть проблема?< /p>
Редактировать 1: не решено, я просматривал https://learn.microsoft.com/en-us/ef/co ... %2Cfluent- api-simple-key%2Csimple-key и прочитайте, что «включения только одного свойства навигации (без обратной навигации и без свойства внешнего ключа) достаточно, чтобы отношения были определены соглашением». Я подумал, что с «традиционным способом» может возникнуть проблема, поэтому я попытался явно определить взаимосвязь:
Код: Выделить всё
namespace Domain
{
public class ExternalAccount
{
public Guid Id { get; set; }
public string APIKey { get; set; }
public string AppUserForeignKey { get; set; }
public AppUser AppUser { get; set; }
}
}
Код: Выделить всё
using Domain;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
namespace Persistence
{
public class DataContext : IdentityDbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DbSet ExternalAccounts { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity()
.HasOne(u => u.AppUser)
.WithMany(a => a.ExternalAccounts)
.HasForeignKey(k => k.AppUserForeignKey);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.LogTo(message => Debug.WriteLine(message));
}
}
Добавлено ведение журнала, как предложено ниже в комментариях.
Миграция выглядит следующим образом: https://pastebin.com/raw/gLs1suBT
Журнал: https://pastebin.com/raw/GH8V2Y9q
Подробнее здесь: https://stackoverflow.com/questions/749 ... affected-0