mvc 5 프로젝트에서 identiy를 사용 중입니다. 내가 사용자와 쿠폰 모델을 가지고,사용자 목록 업데이트 .net identity 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를 사용합니다. Create UserManager instence 코드 행을 확인하십시오. –
UseManager는 확실히 ApplicationDbContext를 사용하여 데이터베이스에 액세스합니다. 그러나 그것은 주어진 사용자를 업데이트하기 위해 사용하고있는 것과 다른 세션에서 사용자 객체를 얻습니다. 따라서 세션에서 사용자를 선택하고 다른 세션에서 업데이트합니다. 이렇게하면 업데이트가 작동하지 않습니다. –
이것은 일반적인 문제입니다. 동일한 ApplicationDbContext 세션에서 사용자 개체를 가져 오거나 업데이트하는 것이 좋습니다. 업데이트 후에 SaveChanges()를 호출하면됩니다. 이것은 분명히 효과가있을 것입니다. –