简体   繁体   English

ASP.Net MVC创建寄存器错误

[英]ASP.Net MVC Creating a register bug

I have this thing running at my application. 我有这个东西在我的应用程序上运行。 I have 3 tables, 1 main table and 2 other tables that are needed to create the main table, the main table depends on the 2 tables, they are connected with constraints. 我有3个表,1个主表和2个创建主表所需的表,主表依赖于2个表,它们与约束连接。 I have the main table: Word Then I have the two other tables: Difficulties and Category. 我有主表:Word然后我有另外两个表:困难和类别。 I created the Difficulty: Easy and then I created the Category: Nature. 我创造了难度:轻松然后我创造了类别:自然。 So now, I would be able to create as many words as I could with those 2 attributes, but it gives me an error. 所以现在,我可以用这两个属性创建尽可能多的单词,但它给了我一个错误。 I can only create a word if I create this way 如果我创造这种方式,我只能创建一个单词

Dificulty -> Category -> Word Dificulty - > Category - > Word

or 要么

Category -> Difficulty -> Word 类别 - >难度 - >单词

. I can't create a word without making that path and I don't know why. 如果没有这条路,我就无法创造一个词,我不知道为什么。 The values are stored in a database that will be called in 2 ComboBoxes, 1 for the Difficulty and the other one for Category. 这些值存储在一个数据库中,该数据库将在2个ComboBox中调用,1个用于Difficulty,另一个用于Category。 If I wanted to create a word I would need to create a new category and a new difficulty otherwise it will return as null. 如果我想创建一个单词,我需要创建一个新类别和一个新的难度,否则它将返回null。

This is my Model View: 这是我的模型视图:

public partial class palavra
    {
        public int id_pal { get; set; }
        public Nullable<int> LETRAS { get; set; }
        public string PISTA { get; set; }
        public int id_cat { get; set; }
        public int id_dificuldade { get; set; }
        public string nomepalavra { get; set; }

        public virtual  categoria categoria { get; set; }
       public virtual dificuldade dificuldade { get; set; }
    }

This is my Controller: 这是我的控制器:

public ActionResult Index()
        {
            var palavras = db.palavras.Include(p => p.categoria).Include(p => p.dificuldade);
           return View(palavras.ToList());
        }



        // GET: palavras/Create
        public ActionResult Create()
        {
            ViewBag.id_cat = new SelectList(db.categorias, "id_cat", "TIPO_CATEGORIA");
            ViewBag.id_dificuldade = new SelectList(db.dificuldades, "id_dificuldade", "TIPO_DIFICULDADE");
            return View();
        }

        // POST: palavras/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "id_pal,LETRAS,PISTA,id_cat,id_dificuldade,nomepalavra")] palavra palavra)
        {
            if (ModelState.IsValid)
            {
                db.palavras.Add(palavra);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.id_cat = new SelectList(db.categorias, "id_cat", "TIPO_CATEGORIA", palavra.id_cat);
            ViewBag.id_dificuldade = new SelectList(db.dificuldades, "id_dificuldade", "TIPO_DIFICULDADE", palavra.id_dificuldade);
            return View(palavra);
        }

This is my view: 这是我的看法:

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.nomepalavra)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LETRAS)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.PISTA)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.categoria.TIPO_CATEGORIA)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.dificuldade.TIPO_DIFICULDADE)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.nomepalavra)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LETRAS)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.PISTA)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.categoria.TIPO_CATEGORIA)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.dificuldade.TIPO_DIFICULDADE)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.id_pal }) |
            @Html.ActionLink("Details", "Details", new { id=item.id_pal }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.id_pal })
        </td>
    </tr>
}

Whenever I run my code to insert I get this error: 每当我运行我的代码插入时,我都会收到此错误:

An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code EntityFramework.dll中出现“System.Data.Entity.Infrastructure.DbUpdateException”类型的异常,但未在用户代码中处理

Additional information: An error occurred while updating the entries. 附加信息:更新条目时发生错误。 See the inner exception for details. 有关详细信息,请参阅内部异常

When I check the Details it appears that the "Category" table and the "Difficulty" table are null but the others fields are all with the info that I gave them. 当我检查详细信息时,似乎“类别”表和“难度”表为空,但其他字段都包含我给他们的信息。

My Database Schema is the following: 我的数据库架构如下:

Category connects to Word and Difficulty connects to Word. 类别连接到Word,而难度连接到Word。

Both Category and Difficulty are a 1 to many relationship with the table Word. 类别和难度都是与表格Word的1对多关系。

if you are use entity framework you need to defined your constraint at your model there is 2 options, code first or database first 如果您使用实体框架,则需要在模型中定义约束,有2个选项,首先是代码,或者是数据库优先

here my example with database first 这是我的数据库第一个例子

Database First 数据库优先

after you generate your model from db, easy step to create create update delete with scaffolding 从db生成模型后,使用scaffolding轻松创建create update delete

Scaffolding crud 脚手架crud

with scaffolding you much easier to create crud, and if any constraint 使用脚手架更容易创建crud,如果有任何约束

example above you create work with selecting Difficulty / Category yes your dropdownlist will be created automatically 上面的示例您创建了选择难度/类别的工作是的,您的下拉列表将自动创建

example my codes menu creator controller 例如我的代码菜单创建者控制器

   // GET: SystemMenus/Create
    public IActionResult Create()
    {
        ViewData["ParentId"] = new SelectList(_context.SystemMenus, "Id", "Name");      
        ViewData["Color"] = new SelectList(OptionDropdown.GetBackgroundColor(), "Value", "Text");
        ViewData["Size"] = new SelectList(OptionDropdown.GetSize(), "Value", "Text");
        ViewData["Module"] = new SelectList(OptionDropdown.GetModule(), "Value", "Text");
        return View();
    }

    // POST: SystemMenus/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Name,Controller,Action,ParentId,Icon,Module,Description,FixHeader,Color,Size")] SystemMenu systemMenu)
    {
        if (ModelState.IsValid)
        {
            _context.Add(systemMenu);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        ViewData["ParentId"] = new SelectList(_context.SystemMenus, "Id", "Name", systemMenu.ParentId);
        ViewData["Color"] = new SelectList(OptionDropdown.GetBackgroundColor(), "Value", "Text", systemMenu.Color);
        ViewData["Size"] = new SelectList(OptionDropdown.GetSize(), "Value", "Text", systemMenu.Size);
        ViewData["Module"] = new SelectList(OptionDropdown.GetModule(), "Value", "Text", systemMenu.Module);
        return View(systemMenu);
    }

and here my model with recursive constraint parentid 在这里我的模型与递归约束parentid

 public class SystemMenu
{
    public SystemMenu()
    {
        Details = new HashSet<SystemMenu>();
    }


    [Key]
    public int Id { get; set; }

    [StringLength(50)]
    public string Name { get; set; }

    [StringLength(50)]
    public string Controller { get; set; }
    [StringLength(50)]
    public string Action { get; set; }

    [ForeignKey("ParentId")]

    public SystemMenu Parent { get; set; }
    [Display(Name = "Parent")]
    public int? ParentId { get; set; }
    [StringLength(50)]
    public string Icon { get; set; }

    [StringLength(50)]
    public string Module { get; set; }

    [StringLength(200)]
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }
    public bool FixHeader { get; set; }

    [StringLength(50)]
    public string Color { get; set; }

    [StringLength(50)]
    public string Size { get; set; }

    public ICollection<SystemMenu> Details { get; set; }
}

here's my views 这是我的看法

enter code 

 @model NCFramework.Models.System.SystemMenu @{ ViewData["Title"] = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; } <div class="row"> <div class="col-md-4"> <form asp-action="Create"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Controller" class="control-label"></label> <input asp-for="Controller" class="form-control" /> <span asp-validation-for="Controller" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Action" class="control-label"></label> <input asp-for="Action" class="form-control" /> <span asp-validation-for="Action" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="ParentId" class="control-label"></label> <select asp-for="ParentId" class ="form-control" asp-items="ViewBag.ParentId"> <option value="">Select</option> </select> </div> <div class="form-group"> <label asp-for="Icon" class="control-label"></label> <input asp-for="Icon" class="form-control" /> <span asp-validation-for="Icon" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Module" class="control-label"></label> <select asp-for="Module" class="form-control" asp-items="ViewBag.Module"> <option value="">Select</option> </select> <span asp-validation-for="Module" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Description" class="control-label"></label> <input asp-for="Description" class="form-control" /> <span asp-validation-for="Description" class="text-danger"></span> </div> <div class="form-group"> <div class="mt-checkbox-list"> <label class="mt-checkbox mt-checkbox-outline"> @Html.DisplayNameFor(model => model.FixHeader) <input asp-for="FixHeader" class="checkbox-inline" /> <span></span> </label> </div> </div> <div class="form-group"> <label asp-for="Color" class="control-label"></label> <select asp-for="Color" class="form-control" asp-items="ViewBag.Color"> <option value="">Select</option> </select> <span asp-validation-for="Color" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Size" class="control-label"></label> <select asp-for="Size" class="form-control" asp-items="ViewBag.Size"> <option value="">Select</option> </select> <span asp-validation-for="Size" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-default" /> </div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } 

here 这里

the example with asp.net core mvc also you can try with visual studio, these 3 files generated by scaffolding with defined model first 使用asp.net核心mvc的例子也可以尝试使用visual studio,这些3个文件是由脚手架生成的,首先是定义的模型

hoe this helps 锄头有帮助

cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM