【发布时间】:2014-12-26 13:38:39
【问题描述】:
请在这里提供一些帮助。我不知道为什么会出现这个错误。
列名“Blogs_Id1”无效。 列名“Blogs_Id1”无效。 列名“Blogs_Id1”无效。 说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.Data.SqlClient.SqlException:列名“Blogs_Id1”无效。 列名“Blogs_Id1”无效。 列名“Blogs_Id1”无效。
来源错误:
第 84 行: 第 85 行:@{ 第 86 行:foreach(Model.Comments 中的 var 注释){...
这是我的模型
public class Blogs
{
public int Id { get; set; }
[Required, Display(Name = "Title"), MaxLength(100, ErrorMessage = "The {0} should be 100 characters maximum"), MinLength(10, ErrorMessage = "The {0} is too short!")]
public string BlogTitle { get; set; }
[Required, Display(Name ="Post description"),StringLength(500,ErrorMessage ="{0} too large. Should be maximum of 400 characters"),AllowHtml]
public string Description { get; set; }
[Required,MinLength(50,ErrorMessage ="The {0} should be a minimum of 50 characters"),AllowHtml]
public string Body { get; set; }
public DateTime PostDate { get; set; }
public string Author { get; set; }
public string PostImage { get; set; }
public virtual ICollection<Comments> Comments { get; set; }
}
public class Comments
{
public int Id { get; set; }
public string Username { get; set; }
public DateTime Date { get; set; }
[MaxLength(400, ErrorMessage = "Too many characters in comments. Please limit it to 400 characters"), Required]
public string Comment { get; set; }
public int Blogs_Id { get; set; }
}
这是我的数据库代码
CreateTable(
"dbo.Blogs",
c => new
{
Id = c.Int(nullable: false, identity: true),
BlogTitle = c.String(nullable: false, maxLength: 100),
Description = c.String(nullable: false, maxLength: 500),
Body = c.String(nullable: false),
PostDate = c.DateTime(nullable: false),
Author = c.String(),
PostImage = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Comments",
c => new
{
Id = c.Int(nullable: false, identity: true),
Username = c.String(),
Date = c.DateTime(nullable: false),
Comment = c.String(nullable: false, maxLength: 400),
Blogs_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Blogs", t => t.Blogs_Id)
.Index(t => t.Blogs_Id);
已成功创建博客和评论表。但是,当我想访问我也打算显示 cmets 的帖子详细信息时,上面的错误不断出现。
供参考,这里是视图代码(cmets部分)
@{
foreach (var comment in Model.Comments) {
<div class="media">
<div class="media-body">
<img src="~/images/user.png" width="200" height="200" style="margin: 0 15px 15px 0; float:left" alt="user" title="@comment.Username" />
<h4 class="media-heading">
@comment.Username
<small>@comment.Date.ToLongDateString()</small>
</h4>
@comment.Comment
</div>
</div>
}}
感谢您的帮助
【问题讨论】:
-
你在使用实体框架吗?
-
你能告诉我们
CreateTable吗?它看起来像.ToTable和 Fluent Configuration 的自定义包装器 -
您收到 SQL 异常,可能 Blogs_Id1 不是您查询的表的有效列。检查数据库以建模您正在使用的任何框架的映射。
-
@Dan 是的!上面的数据库代码是Ef生成的数据库迁移脚本。但是,最初生成代码时,Blogs_Id1 列作为外键约束自动包含在脚本中,但我将其修改为使用 Blogs_Id 列。