我创建了一个ASP.NET MVC项目,我在SQL Server 2012数据库中上传文件。我创建了一个名为" Conversion"与AspNetUsers表有关系。我此时已经能够上传文件,但我无法在我的数据库中添加UserID。 这是我的转换类:
public class Conversion
{
public int ConversionID { get; set; }
[StringLength(255)]
public string FileName { get; set; }
public byte[] File { get; set; }
public string UserID { get; set; }
[ForeignKey("UserID")]
public virtual ApplicationUser User { get; set; }
}
我的UploadViewModel:
public class UploadViewModels
{
[DisplayName("Select File to Upload")]
public HttpPostedFileBase File { get; set; }
}
这是我的UploadController:
public class UploadController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Index()
{
var model = new UploadViewModels();
return View(model);
}
[HttpPost]
public ActionResult Index(UploadViewModels model)
{
if (!ModelState.IsValid)
{
return View(model);
}
Conversion conversion = new Conversion();
byte[] uploadFile = new byte[model.File.InputStream.Length];
model.File.InputStream.Read(uploadFile, 0, uploadFile.Length);
conversion.FileName = model.File.FileName;
conversion.File = uploadFile;
//conversion.UserID = User.Identity.GetUserName();
db.Conversions.Add(conversion);
db.SaveChanges();
return Content("File Uploaded.");
}
我尝试使用conversion.UserID = User.Identity.GetUserName();
,但它无效,我收到以下错误:
"类型' System.Data.Entity.Infrastructure.DbUpdateException'的例外情况发生在EntityFramework.dll中,但未在用户代码"。
中处理
它发生在db.SaveChanges();
如果我没有使用conversion.UserID = User.Identity.GetUserName();我在数据库中得到一个null
答案 0 :(得分:0)
我已经启用它,它取代了
conversion.UserID = User.Identity.GetUserName();
与
conversion.UserID = User.Identity.GetUserId();
我收到了UserName而不是UserId!它现在正在运作!