System.InvalidOperationException:'属性'DescriptionList'不是实体类型为'候选'的导航属性

时间:2018-07-13 13:54:15

标签: c# asp.net-core

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

这是我的ApplicationContext:

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


}

更新,我现在收到此错误:

  

Message =“当IDENTITY_INSERT设置为OFF时,无法为表'Candidates'中的Identity列插入显式值。”

1 个答案:

答案 0 :(得分:0)

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

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

编辑:

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

第二,更新的问题的错误指示您正在尝试将具有实体的实体插入数据库上下文。如果在数据库中关闭了此功能,则可以将其关闭,也可以使用自动生成的身份创建实体,这可以使用attribute或ModelBuilder实现。

第三件事:

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

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