Skip to main content
 首页 » 编程设计

c#之MVC 3,C#之代码生成的无效列名

2024年02月23日18小虾米

我是 asp.net C# 的新手,正在尝试通过构建一个基于 MVC 3 音乐应用程序的简单 Web 应用程序来学习。到目前为止,我的运行还不错,但我遇到了这个,我无法找出根本原因。请帮忙

我正在构建一个简单的网站,其中列出了项目,然后单击项目可以看到所有表格,然后单击表格可以看到所有列。正在从具有有效数据和定义的 PK/FK 键的 SQL 数据库中获取项目/表/列。我能够从项目导航到表格,并且可以看到表格下的所有列,但是当我单击列链接时,出现如下所述的错误。

错误:“无效的列名称‘Tables_Id’。” SQL 事件探查器在查询中显示了这一列,但我不明白它来自哪里,因为我没有任何这样的列。

Controller 类

public class ProjectController : Controller  // Inherit from base class Controller 
{ 
    DbEntities storeDB = new DbEntities();   //Create Object/instance of class //StorDB is  reference to an object 
 
    public ActionResult Index() 
    { 
        var Name = storeDB.ProjectNM.ToList(); //Use 'var' coz we may have any type returned, 'var' is determined at run time 
        return View(Name);  
    } 
 
    public ActionResult BrowseTables(string Projects)  
    { 
        var ProjectModel = storeDB.ProjectNM.Include ("Tabless") 
        .Single(g => g.Name == Projects); 
 
        return View(ProjectModel); 
    } 
 
    public ActionResult BrowseColumns(string TableIs) 
    { 
        var ProjectModel1 = storeDB.TableNM.Include("Columnss") 
        .Single(g => g.Tbl_Name == TableIs); 
 
        return View(ProjectModel1); 
 
        //var ColumnModel = storeDB.TableNM.Find(TableIs); 
       // return View(ColumnModel); 
 
    } 
} 

其他类

public partial class Projects //Partial class, see comment below 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
 
    public List<Tables> Tabless { get; set; }  //Navigation Property, required so that we can include tables under projects 
 
} 
 
public class Tables 
{ 
    public int Id { get; set; } 
    public int ProjectId { get; set; } 
    public string Tbl_Name { get; set; } 
    public Projects Project { get; set; }   //Class table can have (belong) only one project 
 
    public List<Columns> Columnss { get; set; } //Table can have more than one column 
  } 
 
 public class Columns 
{ 
    public int Id { get; set; } 
    [ForeignKey("Tables")]  
    public int TblId { get; set; } 
    public string Column_Name { get; set; } 
    public string IncludeFlag { get; set; } 
  } 

查看

<ul>  
@foreach (var Tables in Model.Tabless)  
{  
    <li>  
      @Html.ActionLink(Tables.Tbl_Name, "BrowseColumns", new { TableIs = Tables.Tbl_Name })  
    </li>  
}  


来自 SQL 分析器的查询

[Project2].[Tables_Id] AS [Tables_Id] 

如您所见,查询有一个列 [Tables_Id],我不明白为什么它在那里,因为我没有任何这样的列。请帮忙!

请您参考如下方法:

基本上 MVC3 和 EF4 做了很多约定俗成的事情。

我的建议是稍微阅读一下 EF 4.1,让你自己更清楚一些,让它为你复数化你的表名,并使用数据注释(如果你不喜欢中的属性,则使用属性映射)你的模型)来标记你的对象的 Id 属性...

这不一定是您的问题的原因,但我认为当名称/值更合乎逻辑时,您会发现更容易看到探查器和模型中发生的事情。

首先将您的对象单数化:Table、Column 等,甚至使用更具描述性的名称……如果没有其他原因,这将使您更容易阅读和调试,甚至在这里获得更好的答案。