[Solved] Entity Framework Error: property or indexer anynumous type cannot be assigned to-- its read only

sureshMGR
 
on Mar 09, 2021 11:02 PM
Sample_127135.zip
1444 Views

Hi friends,

when i try to select some columns of a table and update values its not working. issue is:  can you help?

property or indexer<anynumous type bool?, Active int?,updatedby datetime cannot be assigned to-- its read only

var imgObj = db.DocDIImage.Where(a => a.DIImageID == imageId).Select(c => new { c.Active, c.UpdatedBy, c.UpdatedDate}).ToList().FirstOrDefault();
imgObj.Active = false;
imgObj.UpdatedBy = int.Parse(HttpContext.Current.Session["UserID"].ToString());
imgObj.UpdatedDate = DateTime.Now;
db.SaveChanges();

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 10, 2021 04:40 AM

Hi sureshMGR,

Anonymous types in C# are immutable and hence do not have property setter methods.

So you can't assign value to them.

You need to select the entity class and set its value to update.

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    CustomerEntities db = new CustomerEntities();
    Customer customer = db.Customers.Where(a => a.CustomerID == 'ALFKI').Select(c => c).FirstOrDefault();
    customer.ContactName = "Mudassar Khan";
    customer.Country = "India";
    db.SaveChanges();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim db As CustomerEntities = New CustomerEntities()
    Dim customer As Customer = db.Customers.Where(Function(a) a.CustomerID = "ALFKI"c).Select(Function(c) c).FirstOrDefault()
    customer.ContactName = "Mudassar Khan"
    customer.Country = "India"
    db.SaveChanges()
End Sub