代码之家  ›  专栏  ›  技术社区  ›  tp45

我无法将外键保存到一对多表中asp.net但是可以插入数据asp.netmvc 5

  •  0
  • tp45  · 技术社区  · 7 年前

    我有两个表aspNetUser和Tutorial我希望注册的aspNetUser能够创建一个Tutorial,我希望将Tutorial数据返回到他们的页面和其他页面,但我正在努力用aspNetUser'id保存教程,我一直在看一对多的文章,但他们只展示了如何做一对多,但我想要的是控制器或视图的代码保存与aspNetUser id教程

    教程模型

    [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>

    Tutorial data has a null foreign key

    所以我一直在尝试这个,同时等待任何帮助。我想到了这个

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

    我就这样改变了我的模特 标识模型 我把虚拟的

    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()
    1 回复  |  直到 7 年前
        1
  •  0
  •   tp45    7 年前

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(Tutorial tutorial)
    {
        if (ModelState.IsValid)
        {
          var UserId = User.Identity.GetUserId();
            Tutorial.UserId = UserId;
            db.Tutorials.Add(tutorial);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
    
        return View(tutorial);
    }
    

    一开始我写的代码是:var UserId=User.Identity.GetUserId();超出if( 模型状态.isvalid)它不起作用,它给了我一个无效的参考。我要谢谢你 Brendan Green ,

    ahmed-abdi pathan-faisal 谢谢你帮我。