How to update linq to sql values with select new keyword with anonymous types because I am using var
keyword with select new query I need in in this but it returns an error like this
Compiler Error Message: CS0200: Property or indexer 'AnonymousType#1.Code' cannot be assigned to -- it is read only
This is my code:
var ProjectView12 = (from x in db.Projects
select new
{
add = db.Locations.Where(y = > y.ID == x.RegionID).FirstOrDefault().Name,
Province = db.Locations.Where(y = > y.ID == x.ProvinceID).FirstOrDefault().Name,
District = db.Locations.Where(y = > y.ID == x.DistrictID).FirstOrDefault().Name,
Code = x.Code,
Name = x.Name,
ProjectIdentificationDate = db.Milestones.Where(y = > y.ProjectID == x.ID && y.StageID == 1 && y.ComponentID == 1 && y.ModuleID == 1).FirstOrDefault().Date.ToString(),
ProjectLat = Convert.ToDecimal(x.Lat),
ProjectLong = Convert.ToDecimal(x.Lon),
Remarks = db.Milestones.Where(y = > y.ProjectID == x.ID && y.StageID == 1 && y.ComponentID == 1 && y.ModuleID == 1).FirstOrDefault().Remarks.ToString(),
}).ToList();
foreach(var item in ProjectView12)
{
item.Code = txtSubProjectCode.Text;
item.Name = txtSubProjectName.Text;
item.ProjectLat = Convert.ToDecimal(txtLatitude.Text);
item.ProjectLong = Convert.ToDecimal(txtLongitude.Text);
item.ProjectIdentificationDate = txtDate.Text;
item.Remarks = txtRemarks.Text;
} // txtLocation.Text = item.Region + ">" + item.Province + ">" + item.District;
try
{
db.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
Well, you're getting the compiler error because - as it says - the properties of anonymous types are read-only in C#.
More fundamentally, even if you could modify them, you'd have to expect LINQ to SQL to reverse whatever you put into your projection in order to update the original tables. That seems a fairly tall order to me - particularly for the Remarks
property in this particular case.
Basically, in order to update the database, you need to make changes to the entities that are mapped from your tables. Make your query select the relevant entities, then you can project from those later on in client-side code, if necessary - so long as you've still got a reference to the entity to modify.
See more on this question at Stackoverflow