簡體   English   中英

可能檢測到 Object 周期

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM