我有一个表格,用户可以输入他们的火车信息。保存后,我还想将当前用户保存在表中。我在我的模型中建立了一对多的关系,但无法让用户进入我的保存方法。我尝试过多种方式使用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();
}
}
}
答案 0 :(得分:1)
您只需要保存对当前用户的引用。
User.Identity.GetUserId();//this will return your UserID
编辑:User.Identity
如果他们继承Controller