2
在mvc 5項目中使用標識。 我有用戶和優惠券模式,更新用戶列表.net標識usermanager
public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public string Surname { get; set; }
public int TeamId { get; set; }
public int AvatarId { get; set; }
public DateTime RegisterationDate { get; set; }
public virtual Avatar Avatar { get; set; }
public ApplicationUser()
{
this.Coupons = new HashSet<Coupon>();
}
public virtual ICollection<Coupon> Coupons { get; set; }
}
券
public class Coupon
{
public long Id { get; set; }
public string Barcode { get; set; }
public DateTime Date{ get; set; }
public float Bet { get; set; }
public Double Price { get; set; }
public bool System { get; set; }
public Double TotalGain { get; set; }
public int Status { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual CouponDetail CouponDetail { get; set; }
}
有用戶和優惠券之間的關係。
我想用UserManager更新用戶優惠券列表。
private void InsertCoupon(Coupon coupon)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var userId = User.Identity.GetUserId();
if(userId != null){
var user = userManager.FindById(userId);
user.Coupons.Add(coupon);
userManager.UpdateAsync(user);
}
}
代碼工作,但沒有插入優惠券表上。我如何使用優惠券列表更新用戶?這段代碼返回
是的,但UserManager使用ApplicationDbContext。選中創建UserManager的失敗代碼行。 –
Your UseManager肯定使用ApplicationDbContext來訪問數據庫。但是它獲取的用戶對象與您用來更新給定用戶的會話不同。所以,你在會話中選擇用戶並在另一個會話中更新它。如果你這樣做,你的更新將永遠不會工作。 –
這是一個常見問題。只需嘗試在同一個ApplicationDbContext會話中更新用戶對象並在更新後調用SaveChanges()。這一定會奏效。 –