c# 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 = 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 }。如果你做一个select 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引用的对象(select it)

相关内容

  • 没有找到相关文章

最新更新