У меня есть две таблицы aspNetUser и Tutorial. Я хочу, чтобы зарегистрированный aspNetUser мог создавать учебник, и я хочу вернуть данные учебника на их страницу и другие страницы, но я борюсь с сохранением учебника с aspNetUser'id, я просматривал одну-много статей, но они показывают только, как сделать одну-много, но мне нужен код контроллера или представления для сохранения учебника с идентификатором aspNetUser
Буду признателен за любую помощь, вот мой код ниже:
Модель учебника
[Table("Tutorial")]
public class Tutorial
{
[Key]
public int TutorialId { get; set; }
public string Topic { get; set; }
[Required(ErrorMessage = "Course Name is required")]
[Display(Name = "Course Name")]
public string CoursesName { get; set; }
[Required(ErrorMessage = "Discription is required")]
public string Description { get; set; }
[AllowHtml]
public string Content { get; set; }
public ApplicationUser User { get; set; }
}
Идентификационная модель
я изменил это так
public class ApplicationUser : IdentityUser
{
public ICollection<Tutorial> Tutorials { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
и в моем контроллере
Создание и редактирование
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "TutorialId,Topic,CoursesName,Description,Content")] Tutorial tutorial)
{
if (ModelState.IsValid)
{
db.Tutorials.Add(tutorial);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(tutorial);
}
// GET: Tutorial/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tutorial tutorial = await db.Tutorials.FindAsync(id);
if (tutorial == null)
{
return HttpNotFound();
}
return View(tutorial);
}
И, наконец, мой Создать представление
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Tutorial</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Topic, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Topic, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Topic, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CoursesName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CoursesName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CoursesName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Данные учебника имеют нулевой внешний ключ
Так что я пробовал это в ожидании любой помощи. Я придумал это
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Create(Tutorial Tutorial)
{
var user = new ApplicationUser();
if (ModelState.IsValid)
{
db.Tutorials.Add(new Tutorial {
UserId = user.Id//i get the current user id but i cant insert it with the other data
});
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Tutorial);
}
и я сменил модель так
IdentityModels
я ставлю виртуальный
public virtual ICollection<Tutorial> Tutorials { get; set; }
Обучающая модель
[ForeignKey("User")]
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
Создать вид
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Tutorial</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Topic, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Topic, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Topic, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CoursesName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CoursesName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CoursesName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
</div>
</div>
@*@Html.HiddenFor(model => model.User.Id)*@
@*<div class="form-group">
@Html.LabelFor(model => model.UserId, "UserId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("UserId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })
</div>
</div>*@
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
но я получаю эту ошибку
> System.Data.Entity.Validation.DbEntityValidationException
HResult=0x80131920
Message=Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at KLUE_Inc.Controllers.TutorialController.Create(Tutorial Tutorial) in C:\Users\raliq\Music\KLUE Inc\KLUE Inc\Controllers\TutorialController.cs:line 40
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()