c#Linq无法更新记录

时间:2011-04-14 22:30:40

标签: 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 = 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;
}

2 个答案:

答案 0 :(得分:1)

由于您执行了select new { c.UserID, c.PostDate, c.Comment, c.LastEdit },因此会抛出错误。如果您执行select c,您的代码应该有效。

new {...}为您提供了一个无法更新的匿名类型。

答案 1 :(得分:1)

根据错误消息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引用的对象(选择它)