如何在保存对象时将当前用户保存在另一个表中

本文关键字:保存 存在 用户 另一个 对象 | 更新日期: 2023-09-27 18:14:03

我有一个表单,用户将在其中输入他们的火车信息。保存时,我还希望将当前用户保存到表中。我在模型中建立了一对多关系,但不能让用户进入我的保存方法。我试过使用ApplicationUser的一些方法,但不能让它正确发布。下面是我当前的保存方法:

  public void SaveCar(Cars carToSave) {
        if (carToSave.Id == 0) {
            _db.Cars.Add(carToSave);
            _db.SaveChanges();
        } else {
            var original = this.Find(carToSave.Id);
            original.EmptyOrLoaded = carToSave.EmptyOrLoaded;
            original.CarType = carToSave.CarType;
            original.ShippedBy = carToSave.ShippedBy;
            original.RailcarNumber = carToSave.RailcarNumber;
            _db.SaveChanges();
        }
    }

和我的模型类:

 namespace Train.Models {
public class Cars {
    public int Id { get; set; }
    public string EmptyOrLoaded { get; set; }
    public string CarType { get; set; }
    //Hopper, flatbed, tank, gondola, etc.
    public string ShippedBy { get; set; }
    //UP(Union Pacific) or BNSF
    public string RailcarNumber { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

和IdentityModels.cs

  public class ApplicationUser : IdentityUser {
    [StringLength(250, ErrorMessage = "About is limited to 250 characters in length.")]
    public string Company { get; set; }
    public virtual ICollection<Cars> Cargroup { get; set; }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType) {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
        // Add custom user claims here
        return userIdentity;
    }
}
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
    public IDbSet<Cars> Cars { get; set; }
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false) {
    }
    public static ApplicationDbContext Create() {
        return new ApplicationDbContext();
    }
}

}

如何在保存对象时将当前用户保存在另一个表中

您只需要保存对当前用户的引用。

User.Identity.GetUserId();//this will return your UserID

EDIT: User.Identity在您的控制器中可用,如果他们继承Controller