c# Linq不能更新记录

本文关键字:新记录 更新 不能 Linq | 更新日期: 2023-09-27 17:50:10

我试图用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;
}

c# Linq不能更新记录

错误抛出,因为您执行了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)