efcore
efcore copied to clipboard
Generate Update SQL script on add entity with primary key
I'm trying add new children entity with primary key (Guid), but I have exception.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp1.Any
{
class Program
{
static async Task Main()
{
using (var dbq = new MyContext())
{
#region TestData
//var users = new List<User>()
// {
// new User(new[] {"a1", "a2" }),
// };
//dbq.Users.AddRange(users);
//await dbq.SaveChangesAsync();
#endregion TestData
var u = await dbq.Users
.Include(a => a.Props)
.FirstOrDefaultAsync();
u.Add("erhehwe");
await dbq.SaveChangesAsync();
Console.WriteLine($"");
}
Console.WriteLine("End!");
Console.ReadKey();
}
}
public class User
{
private User() { }
public User(string[] names)
{
Props = names.Select(a => new UserProp()
{
Name = a,
}).ToList();
Name = string.Join(", ", Props.Select(a => a.Name));
}
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; }
public ICollection<UserProp> Props { get; set; }
public void Add(string name)
{
Props.Add(new UserProp { Name = name });
}
}
public class UserProp
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid UserId { get; set; }
public string Name { get; set; }
}
public class MyContext : DbContext
{
public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseLoggerFactory(MyLoggerFactory)
.UseNpgsql("Host=localhost;port=5432;Database=test1;Username=postgres;Password=postgres")
;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(a => a.Props)
.WithOne()
.HasForeignKey(a => a.UserId);
}
}
}
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 3.1.6 initialized 'MyContext' using provider 'Npgsql.EntityFrameworkCore.PostgreSQL' with options: None
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (23ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT t."Id", u0."Id", u0."Name", u0."UserId"
FROM (
SELECT u."Id"
FROM "Users" AS u
LIMIT 1
) AS t
LEFT JOIN "UserProp" AS u0 ON t."Id" = u0."UserId"
ORDER BY t."Id", u0."Id"
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (58ms) [Parameters=[@p2='?' (DbType = Guid), @p0='?', @p1='?' (DbType = Guid)], CommandType='Text', CommandTimeout='30']
UPDATE "UserProp" SET "Name" = @p0, "UserId" = @p1
WHERE "Id" = @p2;
Unhandled exception. 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.
at Npgsql.EntityFrameworkCore.PostgreSQL.Update.Internal.NpgsqlModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(DbContext _, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at ConsoleApp1.Any.Program.Main() in C:\Projects\Tests\Sendbox\ConsoleApp1\Any\DBSimple.cs:line 35
at ConsoleApp1.Any.Program.<Main>()
C:\Projects\Tests\Sendbox\ConsoleApp1\bin\Debug\net5.0\ConsoleApp1.exe (process 24428) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .
EF Core version: 3.1.6 Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer) "Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.4" Target framework: (e.g. .NET 5.0) netcoreapp3.1
I expected SQL "INSERT", but I have "UPDATE". If key without Guid.NewGuid(), it is work good
With NET5.0 and EntityFrameworkCore 5.0.0 result exception.
@kvv842 You'll need to mark the GUID key property to not have an automatically generated value. See https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.x/breaking-changes#dc for more information.