C# 保存对象时,如何将当前用户保存到另一个表中?
我有一个表单,用户可以在其中输入他们的车厢信息。保存时,我还希望在表中保存当前用户。我在模型中建立了一对多关系,但无法让用户进入我的保存方法。我尝试了多种方法使用ApplicationUser,但无法使其正确发布。以下是我当前的保存方法:C# 保存对象时,如何将当前用户保存到另一个表中?,c#,asp.net,C#,Asp.net,我有一个表单,用户可以在其中输入他们的车厢信息。保存时,我还希望在表中保存当前用户。我在模型中建立了一对多关系,但无法让用户进入我的保存方法。我尝试了多种方法使用ApplicationUser,但无法使其正确发布。以下是我当前的保存方法: public void SaveCar(Cars carToSave) { if (carToSave.Id == 0) { _db.Cars.Add(carToSave); _db.Save
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();
}
}
公共类应用程序用户:IdentityUser{
[StringLength(250,ErrorMessage=“About长度限制为250个字符。”)]
公共字符串公司{get;set;}
公共虚拟ICollection Cargroup{get;set;}
公共异步任务GenerateUserIdentityAsync(UserManager管理器,字符串身份验证类型){
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是authenticationType);
//在此处添加自定义用户声明
返回用户身份;
}
}
公共类ApplicationDbContext:IdentityDbContext{
公共IDbSet车辆{get;set;}
公共应用程序上下文()
:base(“DefaultConnection”,throwifvv1schema:false){
}
公共静态应用程序上下文创建(){
返回新的ApplicationDbContext();
}
}
}您只需要保存对当前用户的引用
User.Identity.GetUserId();//this will return your UserID
编辑:
用户。如果您的控制器继承了控制器
您的模型类,则您的控制器中可以使用标识
,请?编辑原始以添加模型谢谢。你的用户类呢?如果要通过汽车发布用户数据,用户必须是汽车模型类的属性。编辑以添加标识模型谢谢!我已经试过几次了,但都做不好。我应该把它放在哪里?@ScottVMeyers你应该把它放在你的控制器中,用户。那里有身份。好的,我想我已经知道了,但是我不也需要把它保存在我的保存方法中吗?@ScottVMeyers如果你想把UserID放在你的车里,您应该在模型中定义为Guid,并且当您将Car交给SaveCar方法时,您应该分配Car.UserID=User.Identity.GetUserId();该死,你把我弄丢了。我已将其作为参数添加到控制器的save方法中