简体   繁体   中英

EF Core table first not saving entities in the database

I'm new to EF (table first) and I don't know why these related entities are not saving at all to my database. These are the related entities, UserProfile has a set of Carts

public partial class UserProfile
    {
        public UserProfile()
        {
            Cart = new HashSet<Cart>();
            Naquestions = new HashSet<Naquestions>();
        }

        public int Id { get; set; }
        public string BotUserId { get; set; }
        public int? PrestashopId { get; set; }
        public bool Validated { get; set; }
        public int Permission { get; set; }
        public DateTime CreationDate { get; set; }

        public ICollection<Cart> Cart { get; set; }
        public ICollection<Naquestions> Naquestions { get; set; }
    }

Cart has a set of OrderLines

   public partial class Cart
    {
        public Cart()
        {
            OrderLine = new HashSet<OrderLine>();
            OrderRequest = new HashSet<OrderRequest>();
        }

        public int Id { get; set; }
        public int UserId { get; set; }
        public bool Active { get; set; }

        public UserProfile User { get; set; }
        public ICollection<OrderLine> OrderLine { get; set; }
        public ICollection<OrderRequest> OrderRequest { get; set; }
    }

And when I try to add them:

public async Task AddOrderLineToUser(string botId, OrderLine orderLine)
        {
            using (var context = ServiceProvider.CreateScope())
            {
                var db = context.ServiceProvider.GetRequiredService<GretaDBContext>();

                var user = await UserController.GetUserByBotIdAsync(botId);

                var latestCart = user.Cart.OrderByDescending(c => c.Id).FirstOrDefault();

                if (latestCart != null && latestCart.Active)
                {
                    latestCart.OrderLine.Add(orderLine);
                }
                else
                {
                    var newCart = new Cart()
                    {
                        Active = true,
                    };
                    newCart.OrderLine.Add(orderLine);
                    user.Cart.Add(newCart);
                }

                await db.SaveChangesAsync();
            }
        }

Nothing is saving to the database once db.SaveChangesAsync() is called.

As @Caius Jard said in the comments it seems that user comes from another context. Try

 if (latestCart != null && latestCart.Active)
 {
      orderLine.CartId = latestCart.Id;
      db.OrderLines // I assume it is name of your orderlines DbSet
         .Add(orderLine);
 }
 else
 {
      var newCart = new Cart()
      {
           Active = true,
           UserId = user.Id,
      };
      newCart.OrderLine.Add(orderLine);
      db.Carts // also assuming name of DbSet
         .Add(newCart);
 }

Also you can take a look at Attach method.

But I would say that in general you are doing something not good. Usually creating new scope is not needed, and db context should be injected in corresponding class via ctor. If you still need to create new scope it would make sense to resolve UserController also. Also is UserController an ASP controller?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM