[英]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.我是 EF 新手(表优先),我不知道为什么这些相关实体根本没有保存到我的数据库中。 These are the related entities, UserProfile has a set of Carts
这些是相关的实体,UserProfile 有一组 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购物车有一组 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.调用
db.SaveChangesAsync()
后,没有任何内容保存到数据库中。
As @Caius Jard said in the comments it seems that user
comes from another context.正如@Caius Jard在评论中所说,
user
似乎来自另一个环境。 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.你也可以看看
Attach
方法。
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.
通常不需要创建新的 scope,db context 应该通过 ctor 注入到对应的 class 中。 If you still need to create new scope it would make sense to resolve
UserController
also.如果您仍然需要创建新的 scope,那么解析
UserController
也是有意义的。 Also is UserController
an ASP controller? UserController
也是 ASP controller 吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.