【问题标题】:ASP.NET MVC /Entity Framework Error - Invalid column name 'Environment_Id'ASP.NET MVC /Entity Framework 错误 - 列名“Environment_Id”无效
【发布时间】:2018-09-22 06:56:31
【问题描述】:

我是 ASP.NET MVC 和 EF 的新手,希望这不是一个愚蠢的问题

当我将模型传递给视图时,我收到此错误 - 异常详细信息:System.Data.SqlClient.SqlException:列名“Environment_Id”无效。

模型或数据库表具有该名称的属性。任何人都可以指导我吗?。

  **Here is the Version Model Class**

  public partial class Version
  {
    public Version()
    {
        this.ProfileVersions = new List<ProfileVersion>();
        this.ServerInfoes = new List<ServerInfo>();
    }

    public int Id { get; set; }
    public string Number { get; set; }
    public string Tag { get; set; }
    public string Owner { get; set; }
    public string Approver { get; set; }
    public string Description { get; set; }
    public virtual ICollection<ProfileVersion> ProfileVersions { get; set; }
    public virtual ICollection<ServerInfo> ServerInfoes { get; set; }
}

**Profile Version Class**

public partial class ProfileVersion
{
    public ProfileVersion()
    {
        this.PlatformConfigurations = new List<PlatformConfiguration>();
    }

    public int Id { get; set; }
    public int ProfileId { get; set; }
    public int EnvironmentId { get; set; }
    public int VersionId { get; set; }
    public Nullable<bool> Locked { get; set; }
    public string LockedBy { get; set; }
    public string Comments { get; set; }
    public Nullable<int> Active { get; set; }
    public virtual Environment Environment { get; set; }
    public virtual ICollection<PlatformConfiguration> PlatformConfigurations { get;  
                                                                             set; }
    public virtual PlatformProfile PlatformProfile { get; set; }
    public virtual Version Version { get; set; }
}

**ServerInfo** 
public partial class ServerInfo
{
    public ServerInfo()
    {
        this.PlatformConfigurations = new List<PlatformConfiguration>();
    }

    public int Id { get; set; }
    public string ServerName { get; set; }
    public int ProfileId { get; set; }
    public int VersionId { get; set; }
    public int EnvironmentId { get; set; }
    public string ServerType { get; set; }
    public Nullable<short> Active { get; set; }
    public string Domain { get; set; }
    public string Location { get; set; }
    public string IP { get; set; }
    public string Subnet { get; set; }
    public string Gateway { get; set; }
    public Nullable<int> VLan { get; set; }
    public string DNS { get; set; }
    public string OS { get; set; }
    public string OSVersion { get; set; }
    public string Func { get; set; }
    public Nullable<short> IISInstalled { get; set; }
    public string ADDomainController { get; set; }
    public string ADOrganizationalUnit { get; set; }
    public string ADGroups { get; set; }
    public string LastError { get; set; }
    public Nullable<System.DateTime> LastUpdate { get; set; }
    public virtual Environment Environment { get; set; }
    public virtual ICollection<PlatformConfiguration> PlatformConfigurations { get;      
                                                                             set; }
    public virtual PlatformProfile PlatformProfile { get; set; }
    public virtual Version Version { get; set; }
    public virtual VMConfiguration VMConfiguration { get; set; }
}

 **Controller Code-**

 public ViewResult Index(string id )
    {

        var profileVerList = from ver in _context.Versions
                                where !(from pfv in _context.ProfileVersions
                                    select pfv.VersionId).Contains(ver.Id)
                                select ver;

        var bigView = new BigViewModel
        {
            VersionModel = profileVerList.ToList(),                
        };

        return View(model: bigView);
    }


**In the View where the exception is thrown**

 @Html.DropDownList(
            "SelectedVersionID", 
            new SelectList(
                Model.VersionModel.Select(x => new { Value = x.Id, Text = x.Number}),
                "Value",
                "Text"
                )
            )

【问题讨论】:

  • ProfileVersion 或 ServerInfo 是否有 Environment 属性?
  • 是的 - 他们公共 int EnvironmentId { get;放; } @Olav Nybø
  • 您能更新您的帖子并添加 ProfileVersion 和 ServerInfo 类吗?
  • 已更新!..@ Olav Nybø
  • 问题很可能出在Environment 类中。你能也展示这个类吗(它不在你上面​​的代码 sn-p 中)?

标签: c# asp.net-mvc entity-framework asp.net-mvc-4 entity-framework-4


【解决方案1】:

在您的 ProfileVersionServerInfo 实体中,您有一个 Environment 导航属性。默认情况下,Entity Framework 将尝试创建一个名为 [Property Name]_[Referenced class PK] 的数据库列。在您的场景中,这是Environment_Id。现在的问题是,您还没有进行迁移来创建此数据库列。

如果我不得不想象这里发生了什么,我会说您首先使用 EnvironmentId 属性创建类,迁移,然后决定将导航属性 Environment 添加到每个类,期望 EF 将其与您现有的EnvironmentId 属性。那就是你出错的地方。正如我上面所说,EF 约定是查找名为Environment_Id 的数据库列,因此如果您希望EF 使用EnvironmentId,则只需使用ForeignKey 数据注释告诉它:

[ForeignKey("Environment")]
public int EnvironmentId { get; set; }

【讨论】:

  • 我在 ProfileVersion 和 ServeInfo 中为 EnvironmentId 属性添加了外键数据表示法,但仍然遇到同样的问题 ..@Chris Pratt
  • 您的表中的EnvironmentId 列是否设置为数据库级别的外键?
【解决方案2】:

在我的情况下,我已将我的主键关系添加到同一键.. 所以我只需删除..

【讨论】:

    【解决方案3】:

    我意识到这个问题现在已经 3 年了,但我看到了错误的不同原因 - 在原始问题和我自己的代码中都非常相似。而且,就我而言,我遇到了与上述相同的错误。

    我有一个“MY_ACTIONS”表,其中包含我想添加到下拉列表中的 ID 和名称对。这是模型:

    namespace TestSite.Models
    {
        public class MY_ACTIONS
        {
            //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
            public MY_ACTIONS()
            {
                this.o_actions = new HashSet<MY_ACTIONS>();
            }
    
            [Key]
            public int action_id { get; set; }
    
            [StringLength(100)]
            public string action_name { get; set; }
    
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
            public virtual ICollection<MY_ACTIONS> o_actions { get; set; }
        }
    }
    

    为了让操作显示在下拉列表中,它在我的主表中名为LASTACTIONint 字段中设置了一个ID。在那个模型中,我声明了 ForeignKey 关系:

    namespace TestSite.Models
    {    
    
        [Table("MAIN_TABLE")]
        public partial class MAIN_TABLE
        {
            [Key]
            public int MAIN_TABLE_ID { get; set; }
    
            public int LASTACTION { get; set; } // this would carry a number matching action_id
    
            [ForeignKey("LASTACTION")]
            public virtual MY_ACTIONS MY_ACTIONS { get; set; }
        }
    }
    

    在我的视图中加载此下拉列表时出现错误Invalid column name 'MY_ACTIONS_action_id'

    @Html.DropDownList("lastaction", null, htmlAttributes: new { @class = "form-control" })
    

    ...我在 Controller 函数中使用了这个 ViewBag:

    Model1 db = new Model1(); // database context
    
    MAIN_TABLE o_main = new MAIN_TABLE();
    o_main.lastaction = 2;
    
    ViewBag.lastaction = new SelectList(db.MY_ACTIONS, "action_id", "action_name", o_main.lastaction);
    

    如果我没有声明我的 FK 关系:

    [ForeignKey("LASTACTION")]
    public virtual MY_ACTIONS MY_ACTIONS { get; set; }
    

    我可能也会遇到同样的问题。拥有一个虚拟实例的表示需要将它与一些物理属性联系起来。这类似于:

    public virtual Environment Environment { get; set; }
    

    应该是:

    [ForeignKey("EnvironmentId")]
    public virtual Environment Environment { get; set; }
    

    ProfileVersion 类中,在上面的问题中,假设EnvironmentId 是名为Environment 的表中的主键(该模型未在上面显示)。

    不过,对我来说,我已经遇到了,但我仍然收到错误,所以这样做可能仍然无法解决所有问题。

    结果我所要做的就是在MY_ACTIONS 模型和this.o_actions = new HashSet&lt;MY_ACTIONS&gt;(); 行中去掉那个ICollection&lt;MY_ACTIONS&gt; o_actions,这一切都很好。

    上面的问题中有很多这样的列表和ICollections,所以我敢打赌,拥有它们也会有问题。从一个代表字段的普通模型开始,然后添加代表与外键链接的表的虚拟对象。然后你确保你的下拉列表加载。只有在那之后,你才应该开始添加你的ICollectionsHashSetsLists&lt;T&gt; 和其他实际上不是数据库物理部分的设施——这可能会让 Entity Framework 认为它需要对它们做一些事情没必要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多