我一直在 youtube http://www.youtube.com/watch?v=WwmUFTWEh6Y上完成教程的早期阶段
public ActionResult Update(int? id, string title, string body, DateTime dateTime, string tags)
{
if (!IsAdmin)
{
return RedirectToAction("Index");
}
Post post = GetPost(id);
post.Title = title;
post.Body = body;
post.DateTime = dateTime;
post.Tags.Clear();
tags = tags ?? string.Empty;
string[] tagNames = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string tagName in tagNames)
{
post.Tags.Add(GetTag(tagName));
}
if (!id.HasValue)
{
model.AddToPosts(post);
}
model.SaveChanges();
return RedirectToAction("Details", new { id = post.ID });
}
public ActionResult Edit(int? id)
{
Post post = GetPost(id);
StringBuilder tagList = new StringBuilder();
foreach (Tag tag in post.Tags)
{
tagList.AppendFormat("{0} ", tag.Name);
}
ViewBag.Tags = tagList.ToString();
return View(post);
}
private Tag GetTag(string tagName)
{
return model.Tags.Where(x => x.Name == tagName).FirstOrDefault() ?? new Tag() { Name = tagName };
}
private Post GetPost(int? id)
{
return id.HasValue ? model.Posts.Where(x => x.ID == id).First() : new Post() { ID = -1 };
}
我收到一个 aspx 错误“当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'Posts' 中插入标识列的显式值。” 我知道这是因为它试图在数据库更新时插入 ID 为 -1 而我不希望这样。如果我传入-1,它应该只创建一个新ID吗?这就是教程中发生的事情。我不知道为什么我的行为不同。
==================================================== ========= 编辑 数据库是使用数据库设计器创建的,而不是通过代码创建的,但我查看了代码,但看不到任何自动生成的属性或 IsDbGenerated 属性,我到底应该在哪里插入这个?
// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="CollateralSystems.Models", Name="Post")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class Post : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new Post object.
/// </summary>
/// <param name="id">Initial value of the ID property.</param>
/// <param name="title">Initial value of the Title property.</param>
/// <param name="dateTime">Initial value of the DateTime property.</param>
/// <param name="body">Initial value of the Body property.</param>
public static Post CreatePost(global::System.Int32 id, global::System.String title, global::System.DateTime dateTime, global::System.String body)
{
Post post = new Post();
post.ID = id;
post.Title = title;
post.DateTime = dateTime;
post.Body = body;
return post;
}
#endregion
#region Primitive Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
///
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ID
{
get
{
return _ID;
}
set
{
if (_ID != value)
{
OnIDChanging(value);
ReportPropertyChanging("ID");
_ID = StructuralObject.SetValidValue(value);
ReportPropertyChanged("ID");
OnIDChanged();
}
}
}
private global::System.Int32 _ID;
partial void OnIDChanging(global::System.Int32 value);
partial void OnIDChanged();