我是asp.net C#的新手,并试图通过构建一个基于MVC 3音乐应用程序的简单Web应用程序来学习。到目前为止,我有一个不错的运行,但我遇到这个,我无法找出根本原因。请帮忙
我正在构建一个简单的网站,其中列出了项目,然后单击您看到所有表格的项目,然后单击表格,您会看到所有列。正在从SQL db中提取项目/表/列,其中定义了有效数据和PK / FK密钥。我能够从项目导航到表格,并且可以查看表格下的所有列,但是当我点击列链接时,我会收到如下所述的错误。
错误:“列名称'Tables_Id'无效。” SQL探查器在查询中显示此列,但我不明白它来自何处,因为我没有任何这样的列。
控制器类
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],我不理解为什么它存在,因为我没有任何这样的列。请帮忙!
答案 0 :(得分:2)
基本上MVC3和EF4在常规上做了很多事情。
我建议让自己稍微清楚一些,稍微阅读一下EF 4.1,让它为你复数表名,并使用数据注释(或属性映射,如果你不喜欢中的属性)你的模型)来标记你对象的Id属性......
这不一定是您的问题的原因,但我认为当名称/值更具逻辑意义时,您会发现在分析器和模型中发生的事情要容易得多。
首先选择您的对象:表格,列等,甚至使用更具描述性的名称......如果没有其他原因,您将更容易阅读和调试,或者甚至在这里获得更好的答案。
答案 1 :(得分:2)
EF4.1和外键的约定是将它们命名为{TableName}_{ColumnName}
,因此表的外键需要列名Table_Id
(因为Table是表的名称,而Id是PK列的名称。
这可能会有所帮助:EF 4.1 messing things up. Has FK naming strategy changed?