[英]Possible Object Cycle Detected
我正在尝试将ProductGateway
添加到数据库并为其分配用户。 我得到一个A possible object cycle was detected
。 错误,但我不确定如何克服这个问题。
这是一个使用 Entity Framework Core 的 1:M 关系。 我也在.NET 6。
这个想法是,用户可以在没有任何产品的情况下存在于数据库中,但产品必须分配给用户。
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;
这是 UserGateway model 上的属性
public string Auth0Id { get; set; }
public List<ProductGateway> Products { get; set; }
和产品网关 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; }
我提前感谢任何帮助! 干杯
编辑:这是我的背景 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;
}
}
}
您在 productGateways 中有 userId,因此它已经有对用户的引用。 然后在 productGateway 中再放一个对 User 的引用。 之后,您将 productGateways 列表放入用户列表。 这里循环用户 -> ProductGateway -> 用户 -> productGateway -> 无限。
尝试删除foreach
和_repository.Update(user);
打电话,也许会有帮助。 无论如何你应该只留下一个声明(添加或更新)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.