C# c Linq无法更新记录
我正在尝试使用LINQ更新记录,但出现以下错误:C# c Linq无法更新记录,c#,asp.net,sql,linq,C#,Asp.net,Sql,Linq,我正在尝试使用LINQ更新记录,但出现以下错误: Property or indexer 'AnonymousType#1.Comment' cannot be assigned to -- it is read only Property or indexer 'AnonymousType#1.LastEdit' cannot be assigned to -- it is read only 这是在以下行中抛出的: // Update parent comment q.Comment =
Property or indexer 'AnonymousType#1.Comment' cannot be assigned to -- it is read only
Property or indexer 'AnonymousType#1.LastEdit' cannot be assigned to -- it is read only
这是在以下行中抛出的:
// Update parent comment
q.Comment = EditedText;
q.LastEdit = DateTime.Now;
全套课程如下:
/// <summary>
/// Creates a new edit for a comment
/// </summary>
/// <param name="CommentID">ID of comment we are editing</param>
/// <param name="EditedText">New text for comment</param>
/// <param name="UserID">ID of user making the edit</param>
/// <returns>Status</returns>
public static CommentError NewEdit(int CommentID, string EditedText, int UserID)
{
CommentError Status = CommentError.UnspecifiedError;
using (DataClassesDataContext db = new DataClassesDataContext())
{
bool IsOriginalAuthor = false;
var q = (from c in db.tblComments where c.ID == CommentID select new { c.UserID, c.PostDate, c.Comment, c.LastEdit }).Single();
if (q == null)
Status = CommentError.UnspecifiedError;
else
{
if (q.UserID == UserID)
IsOriginalAuthor = true;
// Check if they are within lock time
bool CanEdit = true;
if (IsOriginalAuthor)
{
if (q.PostDate.AddMinutes(Settings.MinsUntilCommentLockedFromEdits) > DateTime.Now)
{
Status = CommentError.CommentNowUneditable;
CanEdit = false;
}
}
// Passed all checks, create edit.
if (CanEdit)
{
// Update parent comment
q.Comment = EditedText;
q.LastEdit = DateTime.Now;
// New edit record
tblCommentEdit NewEdit = new tblCommentEdit();
NewEdit.CommentID = CommentID;
NewEdit.Date = DateTime.Now;
NewEdit.EditedText = EditedText;
NewEdit.UserID = UserID;
db.tblCommentEdits.InsertOnSubmit(NewEdit);
db.SubmitChanges();
Status = CommentError.Success;
}
}
}
return Status;
}
由于执行了select new{c.UserID、c.PostDate、c.Comment、c.LastEdit},因此引发错误。如果你选择c,你的代码应该可以工作。
new{…}为您提供了一个不可更新的匿名类型。根据错误消息,q是一个匿名类型
var q = (from c in db.tblComments where c.ID == CommentID select new { c.UserID, c.PostDate, c.Comment, c.LastEdit }).Single();
您不想更新该对象。。。更新LINQ语句中c引用的对象并选择它