Beim Hinzufügen eines Datensatzes wird für die Verknüpfungsentität eine zufällige EF -Kern -ID generiertC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Beim Hinzufügen eines Datensatzes wird für die Verknüpfungsentität eine zufällige EF -Kern -ID generiert

Post by Anonymous »

Die Essenz des Problems: Ich sende eine Anfrage über Swagger mit den folgenden Daten < /p>

Code: Select all

    {
"title": "string",
"content": "string",
"userId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"categories": [
"3fa85f64-5717-4562-b3fc-2c963f66afa6"
]
}
< /code>
Beim Hinzufügen eines Datensatzes nach Abschluss aller Schritte im Repository wird zum Zeitpunkt des Aufrufens der Addasync -Methode eine zufällige ID für Kategorien generiert. Tatsächlich erstellen Sie eine neue Kategorie -Entität mit einer zufälligen ID und einem leeren Namen und es wird der Datenbank hinzugefügt. поста] [1]] [1] < /p>
upd: Ich werde hinzufügen, dass die Kategorie -ID, die ich in der Anforderung übergibt, in der Datenbank vorliegt. Vielen Dank für Ihre Hilfe
Code: < /p>
/// 
/// DTO of adding a post.
/// 
/// Заголовок.
/// Контент.
/// Id автора поста.
/// Список категорий поста в виде .
public record AddPostRequest(string Title, string Content, Guid UserId, List Categories);

/// 
/// Добавление поста.
/// 
/// Данные поста.
/// .
/// .
private static async Task AddPost(AddPostRequest request,
IPostRepository repository, CancellationToken cancellationToken)
{
var post = request.ToModel();

await repository.Create(post, cancellationToken);

return Results.Ok(new Response(StatusCodes.Status200OK, String.Empty));
}

public static Post ToModel(this AddPostRequest request)
{
var postId = Guid.NewGuid();

var post = new Post()
{
Id = postId,
Title = request.Title,
UserId = request.UserId,
Content = request.Content,
PostCategories = request.Categories.Select(id => new PostCategory()
{
PostId = postId,
CategoryId = id
}).ToList(),
CreatedOn = DateTime.UtcNow,
ModifiedOn = DateTime.UtcNow
};

return post;
}

public async Task Create(Post entity, CancellationToken cancellationToken)
{
if (!entity.PostCategories.Any())
{
Result.Failed($"{nameof(entity.PostCategories)} не может быть пустым.", ResultType.BadRequest);
}

try
{
await context.Database.BeginTransactionAsync(cancellationToken);
await context.Posts.AddAsync(entity, cancellationToken); // тут у категорий почему-то создается новый ID

await context.SaveChangesAsync(cancellationToken);
await context.Database.CommitTransactionAsync(cancellationToken);

return Result.Success(entity);
}
catch (Exception exception)
{
await context.Database.RollbackTransactionAsync(cancellationToken);
throw;
}
}

private static IServiceCollection AddDatabase(this IServiceCollection serviceCollection, string connectionString)
{
serviceCollection.AddNpgsql(connectionString, builder =>
{
builder.EnableRetryOnFailure(DatabaseConfig.RetryOnFailure,
TimeSpan.FromSeconds(30), null).ExecutionStrategy(dependencies => new NpgsqlExecutionStrategy(dependencies));
} );

return serviceCollection;
}

public class CategoryConfiguration : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder builder)
{
builder.ToTable("Category");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).IsRequired();
builder.Property(x => x.Name).IsRequired();
}
}

public class PostCategoryConfiguration : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder builder)
{
builder.ToTable("PostCategoryMap");
builder.HasKey(x => new { x.CategoryId, x.PostId });
builder.Property(x => x.CategoryId);

builder.HasOne(x => x.Post)
.WithMany(x => x.PostCategories)
.HasForeignKey(x => x.PostId);

builder.HasOne(x => x.Category)
.WithMany(x => x.PostCategories)
.HasForeignKey(x => x.CategoryId);
}
}

public class PostConfiguration : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder builder)
{
builder.ToTable("Post");
builder.HasKey(x=> x.Id);
builder.HasIndex(x => x.Id).IsUnique();
builder.Property(x => x.Id).IsRequired();
builder.Property(x => x.Title).IsRequired();
builder.Property(x => x.Content).IsRequired();
builder.Property(x => x.CreatedOn).IsRequired();
}
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post