首页 > 解决方案 > System.InvalidOperationException:'属性'DescriptionList'不是实体类型'Candidate'的导航属性

问题描述

我现在收到此错误,但前一段时间该应用程序运行良好,我只将数据添加到模型中,但未在 CandidateHistory 中使用。我真的不明白为什么它会给我这个错误,因为我没有更改历史控制器上的任何内容,只是将数据添加到其他控制器使用的候选模型......

这是我的应用程序上下文:

using HCCBPOHR.Core.Contracts.Data;
 using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Text;


namespace HCCBPOHR.Data.Context
 {


    public class ApplicationContext : IdentityDbContext<ApplicationUser>
{
    protected IConfiguration _Configuration;

    public IConfiguration Configuration 
    {

        get
        {
            if (_Configuration == null)
            {
                var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");

                _Configuration = builder.Build();
            }

            return _Configuration;
        }
        set
        {
            _Configuration = value;
        }
    }
    public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
    {
    }

    public ApplicationContext()
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionString = Configuration.GetConnectionString("DefaultConnection");

        optionsBuilder.UseSqlServer(connectionString);

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationship.DeleteBehavior = DeleteBehavior.Restrict;
        }
        ConfigAsset(modelBuilder);

        base.OnModelCreating(modelBuilder);
    }

    private void ConfigAsset(ModelBuilder modelBuilder)
    {

    }

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public static IEnumerable<object> ApplicationUser { get; internal set; }
    public DbSet<Profile> Profile { get; set; }
    public DbSet<Ads> Ads { get; set; }
    public DbSet<Area> Area { get; set; }
    public DbSet<Candidate> Candidates { get; set; }
    public DbSet<CandidateAnalytics> CandidateAnalytics { get; set; }


}

}

这是我的控制器:

public IActionResult CandidateHistory(int Id)
    {

        using (var applicationcontext = new ApplicationContext())
        {
            var candidate = applicationcontext.Candidates.Where(s => s.Id.Equals(Id)).SingleOrDefault();
            //var candidate = applicationcontext.Candidates.AsNoTracking().Include(q => q.DescriptionList).Single(q => q.Id == Id); //Recieving all the data from the Candidate With the ID = Id
            if (candidate == null) //if Candidate isn't found return a error page
            {
                return NotFound();
            }


            return View(candidate);
        }
    }

    [HttpPost, ActionName("CandidateHistory")]
    [ValidateAntiForgeryToken]
    public IActionResult CandidateHistoryPost([Bind("Description, State, DateOfDescription, Saving, Interviewer, Feedback, FeedbackDate, Behavior,InterViewDate")]Candidate candidate, int Id)
    {
        try
        {
            if (ModelState.IsValid)
            {
                using (var applicationContext = new ApplicationContext())
                {
                    //var candidates = applicationContext.Candidates.Where(s => s.Id.Equals(Id)).SingleOrDefault();
                    var candidates = applicationContext.Candidates.AsNoTracking().Include(q => q.DescriptionList).Single(q => q.Id == Id);    //Getting all the DATA from the Candidate with the Id passed in the Get Method
                    candidates.DescriptionList.Add(candidates);
                    applicationContext.Candidates.Add(candidates);
                    applicationContext.SaveChanges();
                    return RedirectToAction("CandidateHistory");
                }
            }
        }
        catch (DbUpdateException ex)
        {
            //Log the error (uncomment ex variable name and write a log.
            ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator.");
        }
        return View();
    }

这也是我的观点:

@model HCCBPOHR.Data.Candidate

@{
ViewData["State"] = "CandidateHistory";
 }
<h2>Canidate - @Model.Name</h2>
<label>History</label>
 <hr />
<div class="panel panel-default">
<div class="panel-heading">
    <i class="fa fa-clock-o fa-fw"></i> History Of @Model.Name
</div>
<div class="panel-body">
    @foreach (var Description in Model.DescriptionList)
    {
        @if (Description.Saving == true)
        {
            <ul class="timeline">
                <li class="timeline">
                    <div class="timeline-badge">
                        <i class="fa fa-check"></i>
                    </div>
                    <div class="timeline-panel">
                        <div class="timeline-heading">
                            <h4 class="timeline-title">@Description.State</h4>
                            <p>
                                <small class="text-muted"><i class="fa fa-clock-o"></i> @Description.DateOfDescription.ToShortDateString()</small>
                            </p>
                        </div>
                        <div class="timeline-body">
                            <p><b>Description:</b> @Description.Description</p>
                        </div>
                        <div class="timeline-body">
                            <p><b>Interviewer:</b> @Description.Interviewer</p>
                        </div>
                        <div class="timeline-body">
                            <p><b>Feedback:</b> @Description.Feedback</p>
                        </div>
                        <div class="timeline-body">
                            <p><b>FeedbackDate:</b> @Description.FeedbackDate</p>
                        </div>
                        <div class="timeline-body">
                            <p> <b>Bad behavior:</b> @Description.Behavior</p>
                        </div>
                        <div class="timeline-body">
                            <p> <b>Applied For:</b> @Description.SelectedAd</p>
                        </div>
                    </div>
                </li>
            </ul>
        }
        @if (Description.Saving == false)
        {
            <ul class="timeline">
                <li class="timeline-inverted">
                    <div class="timeline-badge">
                        <i class="fa fa-check"></i>
                    </div>
                    <div class="timeline-panel">
                        <div class="timeline-heading">
                            <h4 class="timeline-title">@Description.State</h4>
                            <p>
                                <small class="text-muted"><i class="fa fa-clock-o"></i> @Description.DateOfDescription.ToShortDateString()</small>
                            </p>
                        </div>
                        <div class="timeline-body">
                            <p><b>Description:</b> @Description.Description</p>
                        </div>
                        <div class="timeline-body">
                            <p><b>Interviewer:</b> @Description.Interviewer</p>
                        </div>
                        <div class="timeline-body">
                            <p><b>Feedback:</b> @Description.Feedback</p>
                        </div>
                        <div class="timeline-body">
                            <p><b>FeedbackDate:</b> @Description.FeedbackDate</p>
                        </div>
                        <div class="timeline-body">
                            <p> <b>Bad behavior:</b> @Description.Behavior</p>
                        </div>
                        <div class="timeline-body">
                            <p> <b>Applied For:</b> @Description.SelectedAd</p>
                        </div>
                    </div>
                </li>
            </ul>
        }
    }
   </div>
 </div>
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@Model.Saving"> Add History Description</button>
  <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-body">
            <form asp-action="CandidateHistory">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="form-group">
                    <label>Estado</label>
                    <select asp-for="State" class="form-control">
                        <option value="FirstIntrerview">First Interview </option>
                        <option value="SecoundInterview">Secound Interview</option>
                        <option value="Contract">Contract</option>
                    </select>
                </div>
                <div class="form-group">
                    <label asp-for="InterViewDate" class="control-label">Interview Date:</label>
                    <input asp-for="InterViewDate" class="form-control" value="" />
                    <span asp-validation-for="InterViewDate" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Description" class="control-label">Description</label>
                    <input asp-for="Description" class="form-control" value="" />
                    <span asp-validation-for="Description" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label>Side of History</label>
                    <select asp-for="Saving" class="form-control">
                        <option value="false">Candidate </option>
                        <option value="true">Hitachi</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Interviewer</label>
                    <select asp-for="Interviewer" class="form-control">
                        <option value="Mananger">Mananger </option>
                        <option value="Diretora">Diretora</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>FeedBack</label>
                    <select asp-for="Feedback" class="form-control">
                        <option value="Yes">Yes </option>
                        <option value="No">No</option>
                    </select>
                </div>
                <div class="form-group">
                    <label asp-for="FeedbackDate" class="control-label">Feedback Date:</label>
                    <input asp-for="FeedbackDate" class="form-control" value="" />
                    <span asp-validation-for="FeedbackDate" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label>Bad Behavior?</label>
                    <select asp-for="Behavior" class="form-control">
                        <option value="Yes">Yes </option>
                        <option value="No">No</option>
                    </select>
                </div>
                <div class="form-group">
                    <label asp-for="DateOfDescription" class="form-group">Date of the HistoryPost</label>
                    <input asp-for="DateOfDescription" class="form-group" />
                    <span asp-validation-for="DateOfDescription" class="text-danger"></span>
                </div>

                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
    </div>
   </div>
 </div>

这是我的候选模型:

 public class Candidate : BaseEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Number { get; set; }
    public string ProfileText { get; set; }
    public Byte[] CV { get; set; }
    public string CVNAME { get; set; }
    public List<Profile> ProfileList { get; set; }
    public string Title { get; set; }
    public String Description { get; set; }
    public Boolean Saving { get; set; }
    public string State { get; set; }
    public DateTime DateOfDescription { get; set; }
    public List<Candidate> DescriptionList { get; set; }
    public DateTime FeedbackDate { get; set; }
    public string Feedback { get; set; }
    public String Interviewer { get; set; }
    public DateTime InterViewDate { get; set; }
    public string Behavior { get; set; }
    public List<Ads> AllAds { get; set; }
    public string SelectedAd { get; set; }
    public int Vacancies { get; set; }
    public List<Candidate> VacanciesFilled { get; set; }
    public int GivenUp { get; set; }
    public int Age { get; set; }
    public Candidate()
    {
        DescriptionList = new List<Candidate>();
        //AllAds = new List<Ads>();
        //VacanciesFilled = new List<Candidate>();
    }


}

更新我现在收到此错误:

消息 =“当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'Candidates' 中插入标识列的显式值。”

标签: c#asp.net-core

解决方案


问题是您没有将描述列表标记为virtual. 使属性虚拟化使其成为导航属性。否则,它只是标量属性。

注意 - 如果您使用的是数据库优先方法,请检查您是否在候选人和描述列表之间创建了关系。

编辑:

如我所见,您甚至没有为您的关系指定外键。然后,使用 EF Core Fluent API 定义OnModelCreating()方法内部的关系。也许这会对你有所帮助。 https://www.learnentityframeworkcore.com/configuration/fluent-api/haskey-method

其次,更新问题的错误表明,您正在尝试将实体与实体插入数据库上下文中。如果在您的数据库中关闭此功能,您可以将其关闭,或者创建具有自动生成标识的实体,您可以使用属性或模型构建器来实现。

第三件事:

candidates.DescriptionList.Add(candidates);
applicationContext.Candidates.Add(candidates);

这很糟糕 - 您必须决定是仅将实体添加到 DbContext 中,手动设置关系,还是添加到 DescriptionList,然后保存上下文。


推荐阅读