我正在嘗試將 a 添加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 模型的屬性
public string Auth0Id { get; set; }
public List<ProductGateway> Products { get; set; }
和 ProductGateway 模型
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; }
我提前感謝任何幫助!干杯
編輯:這是我的背景關系類
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;
}
}
}
uj5u.com熱心網友回復:
您在 productGateways 中有 userId,因此它已經具有對用戶的參考。然后,您在 productGateway 中再添加一個對 User In 的參考。之后,您將 productGateways 串列放入用戶串列。這里回圈用戶 -> ProductGateway -> 用戶 -> productGateway -> 無限。
嘗試洗掉foreach和_repository.Update(user);呼叫,也許它會有所幫助。任何方式你都應該只留下一個宣告(添加或更新)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426637.html
