ScottVMeyers ScottVMeyers - 1 month ago 4
ASP.NET (C#) Question

How do I save current user in another table when saving objects?

I have a form where users will enter their traincar information. When saved, I also want to save the current user in the table. I have a one-to-many relationship built in my models, but can't get the user into my save method. I've tried using ApplicationUser a number of ways but can't get it to post correctly. Here is my current save method:

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();
}
}


And my model class:

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; }

}


And 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();
}
}


}

Answer

You need to save only the reference to the current user.

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

EDIT: User.Identity is available in your Controllers if they inherit Controller

Comments