'Possible Object Cycle Detected
I am trying to add a ProductGateway to a database and assign it a user. I am getting an A possible object cycle was detected. error but I am unsure how I can overcome this.
This is a 1:M relationship using Entity Framework Core. I am also in .NET 6.
The idea is that a user can exist in the database without any products but a product must be assigned a user.
var user = _repository.GetAll<UserGateway>().FirstOrDefault(u => u.Id == userId);
if (user == null) throw new InvalidUserException();
var productGateways = productDtos.Select(productDto => new ProductGateway
{
DateCreated = DateTime.Now,
DateLastModified = DateTime.Now,
Description = productDto.Description,
Quantity = productDto.Quantity,
Title = productDto.Title,
Gsku = productDto.Sku,
ImageUrl = "",
UserId = userId
})
.ToList();
user.Products = productGateways;
foreach (var product in user.Products)
{
product.User = user;
}
_repository.AddRange(productGateways);
_repository.Update(user);
_repository.Commit();
return productGateways;
Here is the properties on the UserGateway model
public string Auth0Id { get; set; }
public List<ProductGateway> Products { get; set; }
And the ProductGateway model
public string Title { get; set; }
public string Gsku { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public string ImageUrl { get; set; }
public UserGateway User { get; set; }
public int UserId { get; set; }
I appreciate any help in advance! Cheers
EDIT: Here is my context class
public class Context : DbContext
{
private readonly IConfiguration _configuration;
private DbSet<ProductGateway> Products { get; set; }
private DbSet<UserGateway> Users { get; set; }
public Context(IConfiguration configuration)
{
_configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = _configuration.GetConnectionString("Context");
optionsBuilder.UseSqlServer(connectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
